package com.ctshk.rpc.air.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.Assert;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.ValidatorUtil;
import com.ctshk.rpc.air.dto.*;
import com.ctshk.rpc.air.dto.ticketop.AirBookingTicketTypeOpDTO;
import com.ctshk.rpc.air.dto.ticketop.AirBookingTicketTypeToursDTO;
import com.ctshk.rpc.air.entity.*;
import com.ctshk.rpc.air.mapper.*;
import com.ctshk.rpc.air.req.*;
import com.ctshk.rpc.air.req.airStrategy.*;
import com.ctshk.rpc.air.service.IAirProductCostService;
import com.ctshk.rpc.air.service.IAirProductCostTouristService;
import com.ctshk.rpc.air.service.IAirProductService;
import com.ctshk.rpc.air.util.AirProductUtil;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.workflow.dto.ApprovalCheckDTO;
import com.ctshk.rpc.workflow.dto.ApprovalStartDTO;
import com.ctshk.rpc.workflow.service.ISysApprovalService;
import com.github.houbb.heaven.util.util.CollectionUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 机票产品 服务实现类
 * </p>
 *
 * @author lihang
 * @since 2021-03-05
 */
@DubboService
public class AirProductServiceImpl extends ServiceImpl<AirProductMapper, AirProduct> implements IAirProductService {

    @Autowired
    private AirProductReservationSettingsMapper airProductReservationSettingsMapper;

    @Autowired
    private AirProductCostMapper airProductCostMapper;

    @Autowired
    private AirProductCostTouristMapper airProductCostTouristMapper;

    @Autowired
    private AirProductCostDateMapper airProductCostDateMapper;

    @Autowired
    private AirFlightMapper airFlightMapper;

    @Autowired
    private AirProductChannelOfflineMapper airProductChannelOfflineMapper;

    @Autowired
    private AirProductChannelOfflineAgentCustomMapper airProductChannelOfflineAgentCustomMapper;


    @Autowired
    private AirProductChannelOfflineSelfCustomMapper airProductChannelOfflineSelfCustomMapper;

    @Autowired
    private AirProductChannelOnlineSelfPlatformMapper airProductChannelOnlineSelfPlatformMapper;

    @Autowired
    private AirProductChannelOnlineThirdPlatformMapper airProductChannelOnlineThirdPlatformMapper;

    @Autowired
    private AirProductSaleStrategyMapper airProductSaleStrategyMapper;

    @Autowired
    private AirProductSaleStrategyVaildDateMapper airProductSaleStrategyVaildDateMapper;

    @Autowired
    private AirProductMapper airProductMapper;


    @Autowired
    private AirProductCostTaxationMapper airProductCostTaxationMapper;

    @Autowired
    private IAirProductCostService iAirProductCostService;

    @Autowired
    private AirProductSaleRecordMapper airProductSaleRecordMapper;

    @DubboReference
    private ISysUserService iSysUserService;

    @DubboReference
    private ISysApprovalService iSysApprovalService;
    @Resource
    private IAirProductCostTouristService iAirProductCostTouristService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(AirProductDataReq req, TokenUser tokenUser) {
        /**判断产品是否重复添加  去重規則，航班+艙位+供應商不能重複存在*/
        QueryWrapper<AirProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AirProduct::getRouteId, req.getRouteId());
        queryWrapper.lambda().eq(AirProduct::getCabinClass, req.getCabinClass());
        queryWrapper.lambda().eq(AirProduct::getSupplierId, req.getSupplierId());
        Integer count = baseMapper.selectCount(queryWrapper);
//        Assert.isTrue(count < 1, SystemError.AIR_PRODUCT_12001);
        if (count > 0) return Result.failed(SystemError.AIR_PRODUCT_12001);
        //获取航班信息
        AirFlight airFlight = airFlightMapper.selectById(req.getRouteId());
//        Assert.nonNull(airFlight, SystemError.AIR_PRODUCT_12023);
        if (Objects.isNull(airFlight)) return Result.failed(SystemError.AIR_PRODUCT_12023);
        //获取舱位等级
        List<AirFlightCabinData> flightCabinData = JSONArray.parseArray(airFlight.getCabinClass(), AirFlightCabinData.class);
//        Assert.notEmpty(flightCabinData, SystemError.AIR_PRODUCT_12024);
        if (CollectionUtils.isEmpty(flightCabinData)) return Result.failed(SystemError.AIR_PRODUCT_12024);
        //需要校验航班舱位是否支持本次添加机票舱位
        long cabinFlag = flightCabinData.stream().filter(item -> item.getCabinId().equals(req.getCabinClass())).count();
//        Assert.isTrue(cabinFlag > 0, SystemError.AIR_PRODUCT_12024);
        if (cabinFlag < 1) return Result.failed(SystemError.AIR_PRODUCT_12024);
        /**判断成本日期是否存在重合 因为最后以后包含在时间范围内 获取时 结束日期加1天*/
        List<AirProductCostAddReq> airProductCostDataReqList = req.getAirProductCostDataReqs();
        /**localDateSet 去除重复日期 localDateSize未去除重复日期时的日期总笔 如果两者不相等 则存在重复日期*/
        Set<LocalDate> localDateSet = Sets.newHashSet();
        int localDateSize = 0;
        for (AirProductCostAddReq airProductCostDataReq : airProductCostDataReqList) {
            List<AirProductCostDateData> airProductCostDateDataList = airProductCostDataReq.getAirProductCostDateDataList();
            for (AirProductCostDateData airProductCostDateData : airProductCostDateDataList) {
                LocalDate dateBegin = airProductCostDateData.getDateBegin();
                LocalDate dateEnd = airProductCostDateData.getDateEnd();
                List<LocalDate> dates = Stream.iterate(dateBegin, date -> date.plusDays(1))
                        .limit(ChronoUnit.DAYS.between(dateBegin, dateEnd))
                        .collect(Collectors.toList());
                localDateSet.addAll(dates);
                localDateSize += dates.size();
            }
        }
        if (localDateSet.size() != localDateSize) {
            return Result.failed(SystemError.AIR_PRODUCT_12002);
        }
        /**机票产品主体信息*/
        AirProduct airProduct = EntityUtil.copy(req, AirProduct.class);//产品主体信息
        airProduct.setSellStatus(0);
        airProduct.setRecommendStatus(0);
        airProduct.setCreateId(tokenUser.getId());
        airProduct.setGmtCreate(LocalDateTime.now());
        airProduct.setModifiedId(tokenUser.getId());
        airProduct.setGmtModified(LocalDateTime.now());
        airProduct.setSource(NumberConstant.ONE.getValue());
        if (null == req.getApprovalStatus()) {
            airProduct.setApprovalStatus(1);//默認為待審批
        }
        airProduct.setCode("AIR_" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd")) + "_" + LocalTime.now().format(DateTimeFormatter.ofPattern("HHmmss")));
        Long airProductId = IdWorker.getId();
        airProduct.setId(airProductId);
        airProduct.setIsDeleted(IsDeletedCode.NO.getCode());
        baseMapper.insert(airProduct);
        /**预订信息*/
        if (null != req.getAirProductReservationSettingsDataReq()) {
            AirProductReservationSettings airProductReservationSettings = EntityUtil.copy(req.getAirProductReservationSettingsDataReq(), AirProductReservationSettings.class);
            /**如果是定时开售,必须输入开始时间和结束时间  售卖类型暂时写数字 后续根据枚举或主数据进行优化*/
            if (airProductReservationSettings.getSaleType().intValue() == 2) {
                if (null == airProductReservationSettings.getSaleBeginDate() || null == airProductReservationSettings.getSaleEndDate()) {
                    return Result.failed(SystemError.AIR_PRODUCT_12003);
                }
            }
            airProductReservationSettings.setAirProductId(airProductId);
            airProductReservationSettings.setCreateId(tokenUser.getId());
            airProductReservationSettings.setGmtCreate(LocalDateTime.now());
            airProductReservationSettings.setModifiedId(tokenUser.getId());
            airProductReservationSettings.setGmtModified(LocalDateTime.now());
            Long airProductReservationSettingsId = IdWorker.getId();
            airProductReservationSettings.setId(airProductReservationSettingsId);
            airProductReservationSettings.setIsDeleted(IsDeletedCode.NO.getCode());
            airProductReservationSettingsMapper.insert(airProductReservationSettings);
        }
        /**成本信息*/
        Set<Long> costTouristTypeSet = Sets.newHashSet();
        for (AirProductCostAddReq airProductCostDataReq : airProductCostDataReqList) {
            /**成本主体*/
            AirProductCost airProductCost = EntityUtil.copy(airProductCostDataReq, AirProductCost.class);
            airProductCost.setAirProductId(airProductId);
            airProductCost.setCreateId(tokenUser.getId());
            airProductCost.setGmtCreate(LocalDateTime.now());
            airProductCost.setModifiedId(tokenUser.getId());
            airProductCost.setGmtModified(LocalDateTime.now());
            Long airProductCostId = IdWorker.getId();
            airProductCost.setId(airProductCostId);
            /**成本日期*/
            List<AirProductCostDateData> airProductCostDateDataList = airProductCostDataReq.getAirProductCostDateDataList();
            for (AirProductCostDateData airProductCostDateData : airProductCostDateDataList) {
                AirProductCostDate airProductCostDate = EntityUtil.copy(airProductCostDateData, AirProductCostDate.class);
                airProductCostDate.setCostId(airProductCostId);
                airProductCostDate.setCreateId(tokenUser.getId());
                airProductCostDate.setGmtCreate(LocalDateTime.now());
                airProductCostDate.setModifiedId(tokenUser.getId());
                airProductCostDate.setGmtModified(LocalDateTime.now());
                airProductCostDate.setDailyStock(airProductCostDataReq.getDailyStock());
                Long airProductCostDateId = IdWorker.getId();
                airProductCostDate.setId(airProductCostDateId);
                airProductCostDateMapper.insert(airProductCostDate);
            }
            List<AirProductCostTouristAddReq> airProductCostTouristDataReqs = airProductCostDataReq.getAirProductCostTouristDataReqList();
            StringBuffer touristIds = new StringBuffer();
            StringBuffer touristNames = new StringBuffer();
            /**成本旅客类型*/
            for (AirProductCostTouristAddReq airProductCostTouristDataReq : airProductCostTouristDataReqs) {
                costTouristTypeSet.add(airProductCostTouristDataReq.getTouristTypeId());
                touristIds.append("," + airProductCostTouristDataReq.getTouristTypeId());
                touristNames.append("," + airProductCostTouristDataReq.getTouristTypeName());
                AirProductCostTourist airProductCostTourist = EntityUtil.copy(airProductCostTouristDataReq, AirProductCostTourist.class);
                airProductCostTourist.setCostId(airProductCostId);
                airProductCostTourist.setCreateId(tokenUser.getId());
                airProductCostTourist.setGmtCreate(LocalDateTime.now());
                airProductCostTourist.setModifiedId(tokenUser.getId());
                airProductCostTourist.setGmtModified(LocalDateTime.now());
                Long airProductCostTouristId = IdWorker.getId();
                airProductCostTourist.setId(airProductCostTouristId);
                airProductCostTouristMapper.insert(airProductCostTourist);
                List<AirProductCostTaxationReq> airProductCostTaxationReqList = airProductCostTouristDataReq.getAirProductCostTaxationReqList();
                if (CollectionUtil.isEmpty(airProductCostTaxationReqList)) {
                    throw new BusinessException(SystemError.AIR_PRODUCT_12018, airProductCostTouristDataReq.getTouristTypeName());
                }
                for (AirProductCostTaxationReq airProductCostTaxationReq : airProductCostTaxationReqList) {
                    if (null == airProductCostTaxationReq.getAmount()) {
                        throw new BusinessException(SystemError.AIR_PRODUCT_12019, airProductCostTouristDataReq.getTouristTypeName(), airProductCostTaxationReq.getTaxationName());
                    }
                    AirProductCostTaxation airProductCostTaxation = EntityUtil.copy(airProductCostTaxationReq, AirProductCostTaxation.class);
                    airProductCostTaxation.setTouristId(airProductCostTouristId);
                    airProductCostTaxation.setCreateId(tokenUser.getId());
                    airProductCostTaxation.setIsDeleted(IsDeletedCode.NO.getCode());
                    airProductCostTaxation.setGmtCreate(LocalDateTime.now());
                    airProductCostTaxation.setModifiedId(tokenUser.getId());
                    airProductCostTaxation.setGmtModified(LocalDateTime.now());
                    airProductCostTaxation.setProductId(airProductId);
                    airProductCostTaxation.setId(IdWorker.getId());
                    airProductCostTaxationMapper.insert(airProductCostTaxation);
                }

            }
            airProductCost.setTouristTypeId(touristIds.substring(1));
            airProductCost.setTouristTypeName(touristNames.substring(1));
            airProductCostMapper.insert(airProductCost);
        }
        return Result.success(airProductId);
    }

    @Override
    public Result<AirProductInfoDTO> info(Long id) {
        /**查询机票信息*/
        AirProduct airProduct = baseMapper.selectById(id);
        if (null == airProduct) {
            return Result.failed(SystemError.AIR_PRODUCT_12004);
        }
        /**查询机票预订信息*/
        QueryWrapper<AirProductReservationSettings> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AirProductReservationSettings::getAirProductId, id);
        AirProductReservationSettings airProductReservationSettings = airProductReservationSettingsMapper.selectOne(queryWrapper);
        /**开始组装返回结果*/
        AirProductInfoDTO airProductInfoDto = EntityUtil.copy(airProduct, AirProductInfoDTO.class);
        AirProductReservationSettingsDataReq airProductReservationSettingsDataReq = EntityUtil.copy(airProductReservationSettings, AirProductReservationSettingsDataReq.class);
        airProductInfoDto.setAirProductReservationSettingsDataReq(airProductReservationSettingsDataReq);

        /**查詢航班信息*/
        AirFlight airFlight = airFlightMapper.selectById(airProduct.getRouteId());
        airProductInfoDto.setArrCityId(airFlight.getArrCityId());
        airProductInfoDto.setArrCityName(airFlight.getArrCityName());
        airProductInfoDto.setCompanyId(airFlight.getCompanyId());
        airProductInfoDto.setCompanyName(airFlight.getCompanyName());
        airProductInfoDto.setDepCityId(airFlight.getDepCityId());
        airProductInfoDto.setDepCityName(airFlight.getDepCityName());
        airProductInfoDto.setDepAirportId(airFlight.getDepAirportId());
        airProductInfoDto.setDepAirportName(airFlight.getDepAirportName());
        airProductInfoDto.setArrAirportId(airFlight.getArrAirportId());
        airProductInfoDto.setArrAirportName(airFlight.getArrAirportName());
        airProductInfoDto.setDepTime(airFlight.getDepTime());
        airProductInfoDto.setArrTime(airFlight.getArrTime());
        airProductInfoDto.setChargeUserName("聯調默認寫死");
        airProductInfoDto.setFlightNumber(airFlight.getFlightNumber());
//        UserDTO user = iSysUserService.loadUserByParam(airProduct.getChargeUserId(), 1);
//        airProductInfoDto.setChargeUserName(user.getCnName());
        /**手动机票产品信息 才组装成本信息*/
        if (airProduct.getSource().intValue() == NumberConstant.ONE.getValue()) {
            /**查询税费信息*/
            QueryWrapper<AirProductCostTaxation> airProductCostTaxationQueryWrapper = new QueryWrapper<>();
            airProductCostTaxationQueryWrapper.lambda().eq(AirProductCostTaxation::getProductId, airProduct.getId());
            List<AirProductCostTaxation> airProductCostTaxationList = airProductCostTaxationMapper.selectList(airProductCostTaxationQueryWrapper);
            //税费先按旅客类型分组
            Map<Long, List<AirProductCostTaxation>> touristTaxationMap = Maps.newHashMap();
            for (AirProductCostTaxation airProductCostTaxation : airProductCostTaxationList) {
                List<AirProductCostTaxation> mapValue = touristTaxationMap.get(airProductCostTaxation.getTouristId());
                if (null == mapValue) {
                    mapValue = Lists.newArrayList();
                }
                mapValue.add(airProductCostTaxation);
                touristTaxationMap.put(airProductCostTaxation.getTouristId(), mapValue);
            }
            /**查询成本信息*/
            QueryWrapper<AirProductCost> costQueryWrapper = new QueryWrapper<>();
            costQueryWrapper.lambda().eq(AirProductCost::getAirProductId, id);
            List<AirProductCost> airProductCostList = airProductCostMapper.selectList(costQueryWrapper);
            Set<Long> costIds = Sets.newHashSet();
            for (AirProductCost airProductCost : airProductCostList) {
                costIds.add(airProductCost.getId());
            }
            /**查询旅客信息*/
            QueryWrapper<AirProductCostTourist> touristQueryWrapper = new QueryWrapper<>();
            touristQueryWrapper.lambda().in(AirProductCostTourist::getCostId, costIds);
            List<AirProductCostTourist> airProductCostTouristList = airProductCostTouristMapper.selectList(touristQueryWrapper);
            Map<Long, List<AirProductCostTourist>> assmleTourMap = Maps.newHashMap();
            for (AirProductCostTourist airProductCostTourist : airProductCostTouristList) {
                List<AirProductCostTourist> mapValue = assmleTourMap.get(airProductCostTourist.getCostId());
                if (null == mapValue) {
                    mapValue = Lists.newArrayList();
                }
                mapValue.add(airProductCostTourist);
                assmleTourMap.put(airProductCostTourist.getCostId(), mapValue);
            }
            /**查询成本有效期信息*/
            QueryWrapper<AirProductCostDate> airProductCostDateQueryWrapper = new QueryWrapper<>();
            airProductCostDateQueryWrapper.lambda().in(AirProductCostDate::getCostId, costIds);
            List<AirProductCostDate> airProductCostDateList = airProductCostDateMapper.selectList(airProductCostDateQueryWrapper);
            Map<Long, List<AirProductCostDate>> assmleDateMap = Maps.newHashMap();
            for (AirProductCostDate airProductCostDate : airProductCostDateList) {
                List<AirProductCostDate> mapValue = assmleDateMap.get(airProductCostDate.getCostId());
                if (null == mapValue) {
                    mapValue = Lists.newArrayList();
                }
                mapValue.add(airProductCostDate);
                assmleDateMap.put(airProductCostDate.getCostId(), mapValue);
            }
            List<AirProductCostDTO> airProductCostDTOList = Lists.newArrayList();
            for (AirProductCost airProductCost : airProductCostList) {
                AirProductCostDTO airProductCostDTO = EntityUtil.copy(airProductCost, AirProductCostDTO.class);
                List<AirProductCostTourist> mapValue = assmleTourMap.get(airProductCost.getId());
                List<AirProductCostTouristDTO> airProductCostTouristDTOList = Lists.newArrayList();
                for (AirProductCostTourist airProductCostTourist : mapValue) {
                    AirProductCostTouristDTO airProductCostTouristDTO = EntityUtil.copy(airProductCostTourist, AirProductCostTouristDTO.class);
                    airProductCostTouristDTO.setTouristTypeId(airProductCostTourist.getTouristTypeId());
                    List<AirProductCostTaxation> airProductCostTaxations = touristTaxationMap.get(airProductCostTourist.getId());
                    List<AirProductCostTaxationDTO> airProductCostTaxationDTOList = EntityUtil.copyList(airProductCostTaxations, AirProductCostTaxationDTO.class);
                    airProductCostTouristDTO.setAirProductCostTaxationDTOList(airProductCostTaxationDTOList);
                    airProductCostTouristDTOList.add(airProductCostTouristDTO);
                }
                List<AirProductCostDate> dateMapValue = assmleDateMap.get(airProductCost.getId());
                List<AirProductCostDateData> airProductCostDateDataList = Lists.newArrayList();
                for (AirProductCostDate airProductCostDate : dateMapValue) {
                    AirProductCostDateData airProductCostDateData = EntityUtil.copy(airProductCostDate, AirProductCostDateData.class);
                    airProductCostDateDataList.add(airProductCostDateData);
                }
                airProductCostDTO.setAirProductCostDateDataList(airProductCostDateDataList);
                airProductCostDTO.setAirProductCostTouristDTOList(airProductCostTouristDTOList);
                airProductCostDTOList.add(airProductCostDTO);
            }
            airProductInfoDto.setAirProductCostDTOList(airProductCostDTOList);
        }
        return Result.success(airProductInfoDto);
    }


    @Override
    public Result<AirProductInfoDTO> info(AirStrategyDayInfoReq req) {
        /**查询机票信息*/
        Long id = req.getId();
        AirProduct airProduct = baseMapper.selectById(id);
        if (null == airProduct) {
            return Result.failed(SystemError.AIR_PRODUCT_12004);
        }
        /**查询机票预订信息*/
        QueryWrapper<AirProductReservationSettings> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AirProductReservationSettings::getAirProductId, id);
        AirProductReservationSettings airProductReservationSettings = airProductReservationSettingsMapper.selectOne(queryWrapper);
        /**开始组装返回结果*/
        AirProductInfoDTO airProductInfoDto = EntityUtil.copy(airProduct, AirProductInfoDTO.class);
        AirProductReservationSettingsDataReq airProductReservationSettingsDataReq = EntityUtil.copy(airProductReservationSettings, AirProductReservationSettingsDataReq.class);
        airProductInfoDto.setAirProductReservationSettingsDataReq(airProductReservationSettingsDataReq);
        /**查詢航班信息*/
        AirFlight airFlight = airFlightMapper.selectById(airProduct.getRouteId());
        airProductInfoDto.setArrCityId(airFlight.getArrCityId());
        airProductInfoDto.setArrCityName(airFlight.getArrCityName());
        airProductInfoDto.setCompanyId(airFlight.getCompanyId());
        airProductInfoDto.setCompanyName(airFlight.getCompanyName());
        airProductInfoDto.setDepCityId(airFlight.getDepCityId());
        airProductInfoDto.setDepCityName(airFlight.getDepCityName());
        airProductInfoDto.setDepAirportId(airFlight.getDepAirportId());
        airProductInfoDto.setDepAirportName(airFlight.getDepAirportName());
        airProductInfoDto.setArrAirportId(airFlight.getArrAirportId());
        airProductInfoDto.setArrAirportName(airFlight.getArrAirportName());
        airProductInfoDto.setDepTime(airFlight.getDepTime());
        airProductInfoDto.setArrTime(airFlight.getArrTime());
        airProductInfoDto.setChargeUserName("聯調默認寫死");
        airProductInfoDto.setFlightNumber(airFlight.getFlightNumber());
        /**开始查询预订策略*/
        LocalDate firstDate = LocalDate.of(req.getYear(), req.getMonth(), 1);//当月第一天
        LocalDate lastDate = firstDate.with(TemporalAdjusters.lastDayOfMonth()).plusDays(1);//当月最后一天
        List<LocalDate> strategyDates = Stream.iterate(firstDate, date -> date.plusDays(1))
                .limit(ChronoUnit.DAYS.between(firstDate, lastDate))
                .collect(Collectors.toList());
        QueryWrapper<AirProductSaleStrategyVaildDate> saleStrategyVaildDateQueryWrapper = new QueryWrapper<>();
        saleStrategyVaildDateQueryWrapper.lambda().eq(AirProductSaleStrategyVaildDate::getProductId, id);
        List<AirProductSaleStrategyVaildDate> airProductSaleStrategyVaildDateList = airProductSaleStrategyVaildDateMapper.selectList(saleStrategyVaildDateQueryWrapper);
        Map<LocalDate, Long> dateStrategyMap = Maps.newHashMap();
        for (AirProductSaleStrategyVaildDate airProductSaleStrategyVaildDate : airProductSaleStrategyVaildDateList) {
            LocalDate timeBegin = airProductSaleStrategyVaildDate.getTimeBegin();
            LocalDate timeEnd = airProductSaleStrategyVaildDate.getTimeEnd();
            List<LocalDate> strategyValiDates = Stream.iterate(timeBegin, date -> date.plusDays(1))
                    .limit(ChronoUnit.DAYS.between(timeBegin, timeEnd.plusDays(1)))
                    .collect(Collectors.toList());
            for (LocalDate strategyValiDate : strategyValiDates) {
                dateStrategyMap.put(strategyValiDate, airProductSaleStrategyVaildDate.getStrategyId());
            }
        }
        /**查询售卖记录*/
        QueryWrapper<AirProductSaleRecord> productSaleRecordQueryWrapper = new QueryWrapper<>();
        productSaleRecordQueryWrapper.lambda().eq(AirProductSaleRecord::getProductId, req.getId());
        productSaleRecordQueryWrapper.lambda().ge(AirProductSaleRecord::getSalesDate, firstDate);
        productSaleRecordQueryWrapper.lambda().lt(AirProductSaleRecord::getSalesDate, lastDate);
        List<AirProductSaleRecord> airProductSaleRecordList = airProductSaleRecordMapper.selectList(productSaleRecordQueryWrapper);
        Map<String, Integer> airProductSaleRecordMap = Maps.newHashMap();
        for (AirProductSaleRecord airProductSaleRecord : airProductSaleRecordList) {
            String key = AirProductUtil.getSaleRecodeMapKey(airProductSaleRecord.getChannel(), airProductSaleRecord.getSalesDate(), airProductSaleRecord.getCustomId(),
                    airProductSaleRecord.getProductId());
            Integer number = airProductSaleRecordMap.get(key);
            if (null == number) {
                airProductSaleRecordMap.put(key, airProductSaleRecord.getSoldNumber());
            } else {
                airProductSaleRecordMap.put(key, airProductSaleRecord.getSoldNumber() + number);
            }
        }

        /**處理線下*/
        QueryWrapper<AirProductChannelOffline> channelOfflineQueryWrapper = new QueryWrapper<>();
        List<AirProductChannelOffline> airProductChannelOfflineList = airProductChannelOfflineMapper.selectList(channelOfflineQueryWrapper);
        Map<Long, List<AirProductChannelOffline>> offlineMap = Maps.newHashMap();
        for (AirProductChannelOffline airProductChannelOffline : airProductChannelOfflineList) {
            List<AirProductChannelOffline> mapValue = offlineMap.get(airProductChannelOffline.getStrategyId());
            if (null == mapValue) {
                mapValue = Lists.newArrayList();
            }
            mapValue.add(airProductChannelOffline);
            offlineMap.put(airProductChannelOffline.getStrategyId(), mapValue);
        }
        /**代理商*/
        QueryWrapper<AirProductChannelOfflineAgentCustom> channelOfflineAgentCustomQueryWrapper = new QueryWrapper<>();
        channelOfflineAgentCustomQueryWrapper.lambda().eq(AirProductChannelOfflineAgentCustom::getProductId, id);
        List<AirProductChannelOfflineAgentCustom> airProductChannelOfflineAgentCustomList =
                airProductChannelOfflineAgentCustomMapper.selectList(channelOfflineAgentCustomQueryWrapper);
        Map<Long, List<AirProductChannelOfflineAgentCustom>> strategyOfflineAgentMap = Maps.newHashMap();
        for (AirProductChannelOfflineAgentCustom airProductChannelOfflineAgentCustom : airProductChannelOfflineAgentCustomList) {
            List<AirProductChannelOfflineAgentCustom> mapValue = strategyOfflineAgentMap.get(airProductChannelOfflineAgentCustom.getOfflineId());
            if (null == mapValue) {
                mapValue = Lists.newArrayList();
            }
            mapValue.add(airProductChannelOfflineAgentCustom);
            strategyOfflineAgentMap.put(airProductChannelOfflineAgentCustom.getOfflineId(), mapValue);
        }
        /**自营*/
        QueryWrapper<AirProductChannelOfflineSelfCustom> channelOfflineSelfCustomQueryWrapper = new QueryWrapper<>();
        channelOfflineSelfCustomQueryWrapper.lambda().eq(AirProductChannelOfflineSelfCustom::getProductId, id);
        List<AirProductChannelOfflineSelfCustom> airProductChannelOfflineSelfCustomList = airProductChannelOfflineSelfCustomMapper.selectList(channelOfflineSelfCustomQueryWrapper);
        Map<Long, List<AirProductChannelOfflineSelfCustom>> strategyOfflineSelfMap = Maps.newHashMap();
        for (AirProductChannelOfflineSelfCustom airProductChannelOfflineSelfCustom : airProductChannelOfflineSelfCustomList) {
            List<AirProductChannelOfflineSelfCustom> mapValue = strategyOfflineSelfMap.get(airProductChannelOfflineSelfCustom.getOfflineId());
            if (null == mapValue) {
                mapValue = Lists.newArrayList();
            }
            mapValue.add(airProductChannelOfflineSelfCustom);
            strategyOfflineSelfMap.put(airProductChannelOfflineSelfCustom.getOfflineId(), mapValue);
        }
        /**查询所有的线上官方渠道*/
        QueryWrapper<AirProductChannelOnlineSelfPlatform> onlineSelfPlatformQueryWrapper = new QueryWrapper<>();
        onlineSelfPlatformQueryWrapper.lambda().eq(AirProductChannelOnlineSelfPlatform::getProductId, id);
        List<AirProductChannelOnlineSelfPlatform> airProductChannelOnlineSelfPlatformList = airProductChannelOnlineSelfPlatformMapper.selectList(onlineSelfPlatformQueryWrapper);
        Map<Long, List<AirProductChannelOnlineSelfPlatform>> strategySelfPlatformMap = Maps.newHashMap();
        for (AirProductChannelOnlineSelfPlatform airProductChannelOnlineSelfPlatform : airProductChannelOnlineSelfPlatformList) {
            List<AirProductChannelOnlineSelfPlatform> mapValue = strategySelfPlatformMap.get(airProductChannelOnlineSelfPlatform.getStrategyId());
            if (null == mapValue) {
                mapValue = Lists.newArrayList();
            }
            mapValue.add(airProductChannelOnlineSelfPlatform);
            strategySelfPlatformMap.put(airProductChannelOnlineSelfPlatform.getStrategyId(), mapValue);
        }
        /**查询所有的线上第三方渠道*/
        QueryWrapper<AirProductChannelOnlineThirdPlatform> onlineThirdPlatformQueryWrapper = new QueryWrapper<>();
        onlineThirdPlatformQueryWrapper.lambda().eq(AirProductChannelOnlineThirdPlatform::getProductId, id);
        List<AirProductChannelOnlineThirdPlatform> airProductChannelOnlineThirdPlatformList =
                airProductChannelOnlineThirdPlatformMapper.selectList(onlineThirdPlatformQueryWrapper);
        Map<Long, List<AirProductChannelOnlineThirdPlatform>> strategyThirdPlatformMap = Maps.newHashMap();
        for (AirProductChannelOnlineThirdPlatform airProductChannelOnlineThirdPlatform : airProductChannelOnlineThirdPlatformList) {
            List<AirProductChannelOnlineThirdPlatform> mapValue = strategyThirdPlatformMap.get(airProductChannelOnlineThirdPlatform.getStrategyId());
            if (null == mapValue) {
                mapValue = Lists.newArrayList();
            }
            mapValue.add(airProductChannelOnlineThirdPlatform);
            strategyThirdPlatformMap.put(airProductChannelOnlineThirdPlatform.getStrategyId(), mapValue);
        }
        List<AirStrategyDayInfoDTO> airStrategyDayInfoDtoList = Lists.newArrayList();
        for (LocalDate strategyDate : strategyDates) {
            Long strategyId = dateStrategyMap.get(strategyDate);
            if (null == strategyId) {
                continue;
            } else {
                List<AirStrategyDayInfoOffLineDTO> airStrategyDayInfoOffLineDtos = Lists.newArrayList();
                List<AirStrategyDayInfoOnLineDTO> airStrategyDayInfoOnLineDtos = Lists.newArrayList();
                AirStrategyDayInfoDTO airStrategyDayInfoDto = new AirStrategyDayInfoDTO();
                airStrategyDayInfoDto.setDate(strategyDate);
                /**線下*/
                List<AirProductChannelOffline> offlineMapValue = offlineMap.get(strategyId);
                if (null == offlineMapValue) {
                    offlineMapValue = Lists.newArrayList();
                }
                Map<Integer, AirProductChannelOffline> offlineTypeMap = Maps.newHashMap();
                for (AirProductChannelOffline airProductChannelOffline : offlineMapValue) {
                    offlineTypeMap.put(airProductChannelOffline.getChannelType(), airProductChannelOffline);
                }
                /**處理自營*/
                AirProductChannelOffline airProductChannelSelfOffline = offlineTypeMap.get(1);
                if (null == airProductChannelSelfOffline) {
                    AirStrategyDayInfoOffLineDTO airStrategyDayInfoOffLineDto = new AirStrategyDayInfoOffLineDTO();
                    airStrategyDayInfoOffLineDto.setName("自營禁售");
                    airStrategyDayInfoOffLineDtos.add(airStrategyDayInfoOffLineDto);
                } else {
                    if (airProductChannelSelfOffline.getVisableType().intValue() == 1) {
                        AirStrategyDayInfoOffLineDTO airStrategyDayInfoOffLineDto = new AirStrategyDayInfoOffLineDTO();
                        airStrategyDayInfoOffLineDto.setName("自營禁售");
                        airStrategyDayInfoOffLineDtos.add(airStrategyDayInfoOffLineDto);
                    } else if (airProductChannelSelfOffline.getVisableType().intValue() == 2) {
                        List<AirProductChannelOfflineSelfCustom> strategyOfflineSelfValue = strategyOfflineSelfMap.get(airProductChannelSelfOffline.getId());
                        AirProductChannelOfflineSelfCustom airProductChannelOfflineSelfCustom = strategyOfflineSelfValue.get(0);
                        AirProductSaleStrategyDataInfoData data = EntityUtil.copy(airProductChannelOfflineSelfCustom, AirProductSaleStrategyDataInfoData.class);
                        AirStrategyDayInfoOffLineDTO airStrategyDayInfoOffLineDto = EntityUtil.copy(airProductChannelOfflineSelfCustom, AirStrategyDayInfoOffLineDTO.class);
                        airStrategyDayInfoOffLineDto.setAirProductSaleStrategyDataInfoData(data);
                        String mapKey = AirProductUtil.getSaleRecodeMapKey(AirProductChannelType.SELF_CUSTTOM.getType(), strategyDate,
                                airProductChannelOfflineSelfCustom.getRelationId(), req.getId());
                        Integer soldNumber = airProductSaleRecordMap.get(mapKey);
                        AirProductUtil.assblemStrategyDesc(airStrategyDayInfoOffLineDto, soldNumber);
                        airStrategyDayInfoOffLineDto.setName("所有部門");
                        airStrategyDayInfoOffLineDtos.add(airStrategyDayInfoOffLineDto);
                    } else {
                        List<AirProductChannelOfflineSelfCustom> strategyOfflineSelfValue = strategyOfflineSelfMap.get(airProductChannelSelfOffline.getId());
                        for (AirProductChannelOfflineSelfCustom airProductChannelOfflineSelfCustom : strategyOfflineSelfValue) {
                            AirStrategyDayInfoOffLineDTO airStrategyDayInfoOffLineDto = EntityUtil.copy(airProductChannelOfflineSelfCustom, AirStrategyDayInfoOffLineDTO.class);
                            AirProductSaleStrategyDataInfoData airProductSaleStrategyDataInfoData = EntityUtil.copy(airProductChannelOfflineSelfCustom,
                                    AirProductSaleStrategyDataInfoData.class);
                            airStrategyDayInfoOffLineDto.setAirProductSaleStrategyDataInfoData(airProductSaleStrategyDataInfoData);
                            String mapKey = AirProductUtil.getSaleRecodeMapKey(AirProductChannelType.SELF_CUSTTOM.getType(), strategyDate,
                                    airProductChannelOfflineSelfCustom.getRelationId(), req.getId());
                            Integer soldNumber = airProductSaleRecordMap.get(mapKey);
                            AirProductUtil.assblemStrategyDesc(airStrategyDayInfoOffLineDto, soldNumber);
                            airStrategyDayInfoOffLineDtos.add(airStrategyDayInfoOffLineDto);
                        }
                    }
                }
                /**處理代理商*/
                AirProductChannelOffline airProductChannelAgentsOffline = offlineTypeMap.get(2);
                if (null == airProductChannelAgentsOffline) {
                    AirStrategyDayInfoOffLineDTO airStrategyDayInfoOffLineDto = new AirStrategyDayInfoOffLineDTO();
                    airStrategyDayInfoOffLineDto.setName("代理商禁售");
                    airStrategyDayInfoOffLineDtos.add(airStrategyDayInfoOffLineDto);
                } else {
                    if (airProductChannelAgentsOffline.getVisableType().intValue() == 1) {
                        AirStrategyDayInfoOffLineDTO airStrategyDayInfoOffLineDto = new AirStrategyDayInfoOffLineDTO();
                        airStrategyDayInfoOffLineDto.setName("代理商禁售");
                        airStrategyDayInfoOffLineDtos.add(airStrategyDayInfoOffLineDto);
                    } else if (airProductChannelAgentsOffline.getVisableType().intValue() == 2) {
                        List<AirProductChannelOfflineAgentCustom> strategyOfflineAgentValue = strategyOfflineAgentMap.get(airProductChannelAgentsOffline.getId());
                        AirProductChannelOfflineAgentCustom airProductChannelOfflineAgentCustom = strategyOfflineAgentValue.get(0);
                        AirStrategyDayInfoOffLineDTO airStrategyDayInfoOffLineDto = EntityUtil.copy(airProductChannelOfflineAgentCustom, AirStrategyDayInfoOffLineDTO.class);
                        AirProductSaleStrategyDataInfoData data = EntityUtil.copy(airProductChannelOfflineAgentCustom, AirProductSaleStrategyDataInfoData.class);
                        airStrategyDayInfoOffLineDto.setAirProductSaleStrategyDataInfoData(data);
                        String mapKey = AirProductUtil.getSaleRecodeMapKey(AirProductChannelType.SELF_CUSTTOM.getType(), strategyDate,
                                airProductChannelOfflineAgentCustom.getAgentId(), req.getId());
                        Integer soldNumber = airProductSaleRecordMap.get(mapKey);
                        AirProductUtil.assblemStrategyDesc(airStrategyDayInfoOffLineDto, soldNumber);
                        airStrategyDayInfoOffLineDto.setName("所有代理商");
                        airStrategyDayInfoOffLineDtos.add(airStrategyDayInfoOffLineDto);
                    } else {
                        List<AirProductChannelOfflineAgentCustom> strategyOfflineAgentValue = strategyOfflineAgentMap.get(airProductChannelAgentsOffline.getId());
                        for (AirProductChannelOfflineAgentCustom airProductChannelOfflineAgentCustom : strategyOfflineAgentValue) {
                            AirStrategyDayInfoOffLineDTO airStrategyDayInfoOffLineDto = EntityUtil.copy(airProductChannelOfflineAgentCustom, AirStrategyDayInfoOffLineDTO.class);
                            AirProductSaleStrategyDataInfoData airProductSaleStrategyDataInfoData = EntityUtil.copy(airProductChannelOfflineAgentCustom,
                                    AirProductSaleStrategyDataInfoData.class);
                            airStrategyDayInfoOffLineDto.setAirProductSaleStrategyDataInfoData(airProductSaleStrategyDataInfoData);
                            String mapKey = AirProductUtil.getSaleRecodeMapKey(AirProductChannelType.SELF_CUSTTOM.getType(), strategyDate,
                                    airProductChannelOfflineAgentCustom.getAgentId(), req.getId());
                            Integer soldNumber = airProductSaleRecordMap.get(mapKey);
                            AirProductUtil.assblemStrategyDesc(airStrategyDayInfoOffLineDto, soldNumber);
                            airStrategyDayInfoOffLineDtos.add(airStrategyDayInfoOffLineDto);
                        }
                    }
                }
                /**处理第三方*/
                List<AirProductChannelOnlineThirdPlatform> airProductChannelOnlineThirdPlatforms = strategyThirdPlatformMap.get(strategyId);
                if (CollectionUtil.isEmpty(airProductChannelOnlineThirdPlatforms)) {
                    AirStrategyDayInfoOnLineDTO airStrategyDayInfoOnLineDTO = new AirStrategyDayInfoOnLineDTO();
                    airStrategyDayInfoOnLineDTO.setPlatformName("第三方渠道禁用");
                    airStrategyDayInfoOnLineDtos.add(airStrategyDayInfoOnLineDTO);
                } else {
                    for (AirProductChannelOnlineThirdPlatform airProductChannelOnlineThirdPlatform : airProductChannelOnlineThirdPlatforms) {
                        AirStrategyDayInfoOnLineDTO airStrategyDayInfoOnLineDto = EntityUtil.copy(airProductChannelOnlineThirdPlatform, AirStrategyDayInfoOnLineDTO.class);
                        airStrategyDayInfoOnLineDto.setPlatformId(airProductChannelOnlineThirdPlatform.getPlatformId());
                        airStrategyDayInfoOnLineDto.setPlatformName(airProductChannelOnlineThirdPlatform.getPlatformName());
                        AirProductSaleStrategyDataInfoData airProductSaleStrategyDataInfoData = EntityUtil.copy(airProductChannelOnlineThirdPlatform,
                                AirProductSaleStrategyDataInfoData.class);
                        airStrategyDayInfoOnLineDto.setAirProductSaleStrategyDataInfoData(airProductSaleStrategyDataInfoData);
                        String mapKey = AirProductUtil.getSaleRecodeMapKey(AirProductChannelType.SELF_CUSTTOM.getType(), strategyDate,
                                airProductChannelOnlineThirdPlatform.getPlatformId(), req.getId());
                        Integer soldNumber = airProductSaleRecordMap.get(mapKey);
                        AirProductUtil.assblemStrategyDesc(airStrategyDayInfoOnLineDto, soldNumber);
                        airStrategyDayInfoOnLineDtos.add(airStrategyDayInfoOnLineDto);
                    }
                }
                /**处理官方*/
                List<AirProductChannelOnlineSelfPlatform> airProductChannelOnlineSelfPlatforms = strategySelfPlatformMap.get(strategyId);
                if (CollectionUtil.isEmpty(airProductChannelOnlineSelfPlatforms)) {
                    AirStrategyDayInfoOnLineDTO airStrategyDayInfoOnLineDTO = new AirStrategyDayInfoOnLineDTO();
                    airStrategyDayInfoOnLineDTO.setPlatformName("官方渠道禁用");
                    airStrategyDayInfoOnLineDtos.add(airStrategyDayInfoOnLineDTO);
                } else {
                    for (AirProductChannelOnlineSelfPlatform airProductChannelOnlineSelfPlatform : airProductChannelOnlineSelfPlatforms) {
                        AirStrategyDayInfoOnLineDTO airStrategyDayInfoOnLineDto = EntityUtil.copy(airProductChannelOnlineSelfPlatform, AirStrategyDayInfoOnLineDTO.class);
                        airStrategyDayInfoOnLineDto.setPlatformId(airProductChannelOnlineSelfPlatform.getChannelId());
                        airStrategyDayInfoOnLineDto.setPlatformName(airProductChannelOnlineSelfPlatform.getChannelName());
                        AirProductSaleStrategyDataInfoData airProductSaleStrategyDataInfoData = EntityUtil.copy(airProductChannelOnlineSelfPlatform,
                                AirProductSaleStrategyDataInfoData.class);
                        airStrategyDayInfoOnLineDto.setAirProductSaleStrategyDataInfoData(airProductSaleStrategyDataInfoData);
                        String mapKey = AirProductUtil.getSaleRecodeMapKey(AirProductChannelType.SELF_CUSTTOM.getType(), strategyDate,
                                airProductChannelOnlineSelfPlatform.getChannelId(), req.getId());
                        Integer soldNumber = airProductSaleRecordMap.get(mapKey);
                        AirProductUtil.assblemStrategyDesc(airStrategyDayInfoOnLineDto, soldNumber);
                        airStrategyDayInfoOnLineDtos.add(airStrategyDayInfoOnLineDto);
                    }
                }
                airStrategyDayInfoDto.setAirStrategyDayInfoOffLineDtoList(airStrategyDayInfoOffLineDtos);
                airStrategyDayInfoDto.setAirStrategyDayInfoOnLineDtoList(airStrategyDayInfoOnLineDtos);
                airStrategyDayInfoDtoList.add(airStrategyDayInfoDto);
            }
        }
        airProductInfoDto.setAirStrategyDayInfoDtoList(airStrategyDayInfoDtoList);
        return Result.success(airProductInfoDto);
    }


    @Override
    public Result edit(AirProductDataReq req, TokenUser tokenUser) {
        long airProductId = req.getId();
        AirProduct dbAirProduct = baseMapper.selectById(airProductId);
        /**判断状态  如果是审批中 则不允许修改*/
        if (dbAirProduct.getApprovalStatus().intValue() == 2 || dbAirProduct.getApprovalStatus().intValue() == 3) {
            return Result.failed(SystemError.AIR_PRODUCT_12005);
        }
        /**判断成本日期是否存在重合 因为最后以后包含在时间范围内 获取时 结束日期加1天*/
        List<AirProductCostAddReq> airProductCostDataReqList = req.getAirProductCostDataReqs();
        if (CollectionUtil.isNotEmpty(airProductCostDataReqList)) {
            /**localDateSet 去除重复日期 localDateSize未去除重复日期时的日期总笔 如果两者不相等 则存在重复日期*/
            Set<LocalDate> localDateSet = Sets.newHashSet();
            int localDateSize = 0;
            for (AirProductCostAddReq airProductCostDataReq : airProductCostDataReqList) {
                List<AirProductCostDateData> airProductCostDateDataList = airProductCostDataReq.getAirProductCostDateDataList();
                for (AirProductCostDateData airProductCostDateData : airProductCostDateDataList) {
                    LocalDate dateBegin = airProductCostDateData.getDateBegin();
                    LocalDate dateEnd = airProductCostDateData.getDateEnd();
                    List<LocalDate> dates = Stream.iterate(dateBegin, date -> date.plusDays(1))
                            .limit(ChronoUnit.DAYS.between(dateBegin, dateEnd))
                            .collect(Collectors.toList());
                    localDateSet.addAll(dates);
                    localDateSize += dates.size();
                }
            }
            if (localDateSet.size() != localDateSize) {
                return Result.failed(SystemError.AIR_PRODUCT_12002);
            }
        }


        /**修改规则 未提交可修改所有信息  审核不通过编辑航班信息不能修改  审批通过只能修改每日库存*/
        AirProduct updateAirPro = EntityUtil.copy(req, AirProduct.class);
        baseMapper.updateById(updateAirPro);
        /**修改机票预订设置*/
        if (null != req.getAirProductReservationSettingsDataReq()) {
            QueryWrapper<AirProductReservationSettings> airProductReservationSettingsQueryWrapper = new QueryWrapper<>();
            airProductReservationSettingsQueryWrapper.lambda().eq(AirProductReservationSettings::getAirProductId, req.getId());
            AirProductReservationSettings airProductReservationSettings = airProductReservationSettingsMapper.selectOne(airProductReservationSettingsQueryWrapper);
            if (null == airProductReservationSettings) {
                airProductReservationSettings = EntityUtil.copy(req.getAirProductReservationSettingsDataReq(), AirProductReservationSettings.class);
                airProductReservationSettings.setModifiedId(tokenUser.getId());
                airProductReservationSettings.setGmtModified(LocalDateTime.now());
                airProductReservationSettings.setCreateId(tokenUser.getId());
                airProductReservationSettings.setGmtModified(LocalDateTime.now());
                airProductReservationSettings.setAirProductId(airProductId);
                airProductReservationSettingsMapper.insert(airProductReservationSettings);
            } else {
                AirProductReservationSettings updateSettings = EntityUtil.copy(req.getAirProductReservationSettingsDataReq(), AirProductReservationSettings.class);
                updateSettings.setModifiedId(tokenUser.getId());
                updateSettings.setGmtModified(LocalDateTime.now());
                updateSettings.setId(airProductReservationSettings.getId());
                airProductReservationSettingsMapper.updateById(airProductReservationSettings);
            }
        }
        //需要提交审批
        if (NumberConstant.TWO.getValue().equals(req.getApprovalStatus())) {
            productAudit(req.getId(), tokenUser);
        }
        /**修改机票成本信息  直接删除原来的成本信息 保存新的成本信息*/
        if (CollectionUtil.isEmpty(airProductCostDataReqList)) {//沒有傳入成本 則不修改成本信息了
            return Result.success(airProductId);
        }
        /**删除成本*/
        QueryWrapper<AirProductCost> costQueryWrapper = new QueryWrapper<>();
        costQueryWrapper.lambda().eq(AirProductCost::getAirProductId, dbAirProduct.getId());
        List<AirProductCost> airProductCostList = airProductCostMapper.selectList(costQueryWrapper);
        Set<Long> costIds = Sets.newHashSet();
        for (AirProductCost airProductCost : airProductCostList) {
            costIds.add(airProductCost.getId());
        }
        airProductCostMapper.delete(costQueryWrapper);
        /**删除旅客信息*/
        QueryWrapper<AirProductCostTourist> touristQueryWrapper = new QueryWrapper<>();
        touristQueryWrapper.lambda().in(AirProductCostTourist::getCostId, costIds);
        airProductCostTouristMapper.delete(touristQueryWrapper);
        /**删除成本时间*/
        QueryWrapper<AirProductCostDate> airProductCostDateQueryWrapper = new QueryWrapper<>();
        airProductCostDateQueryWrapper.lambda().in(AirProductCostDate::getCostId, costIds);
        airProductCostDateMapper.delete(airProductCostDateQueryWrapper);
        /**删除税费*/
        QueryWrapper<AirProductCostTaxation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AirProductCostTaxation::getProductId, airProductId);
        airProductCostTaxationMapper.delete(queryWrapper);
        /**保存新的成本信息*/
        for (AirProductCostAddReq airProductCostDataReq : airProductCostDataReqList) {
            /**成本主体*/
            AirProductCost airProductCost = EntityUtil.copy(airProductCostDataReq, AirProductCost.class);
            airProductCost.setAirProductId(airProductId);
            airProductCost.setCreateId(tokenUser.getId());
            airProductCost.setGmtCreate(LocalDateTime.now());
            airProductCost.setModifiedId(tokenUser.getId());
            airProductCost.setGmtModified(LocalDateTime.now());
            Long airProductCostId = IdWorker.getId();
            airProductCost.setId(airProductCostId);
            /**成本日期*/
            List<AirProductCostDateData> airProductCostDateDataList = airProductCostDataReq.getAirProductCostDateDataList();
            for (AirProductCostDateData airProductCostDateData : airProductCostDateDataList) {
                AirProductCostDate airProductCostDate = EntityUtil.copy(airProductCostDateData, AirProductCostDate.class);
                airProductCostDate.setCostId(airProductCostId);
                airProductCostDate.setCreateId(tokenUser.getId());
                airProductCostDate.setGmtCreate(LocalDateTime.now());
                airProductCostDate.setModifiedId(tokenUser.getId());
                airProductCostDate.setGmtModified(LocalDateTime.now());
                Long airProductCostDateId = IdWorker.getId();
                airProductCostDate.setId(airProductCostDateId);
                airProductCostDateMapper.insert(airProductCostDate);
            }
            List<AirProductCostTouristAddReq> airProductCostTouristDataReqs = airProductCostDataReq.getAirProductCostTouristDataReqList();
            StringBuffer touristIds = new StringBuffer();
            StringBuffer touristNames = new StringBuffer();
            /**成本旅客类型*/
            for (AirProductCostTouristAddReq airProductCostTouristDataReq : airProductCostTouristDataReqs) {
                touristIds.append("," + airProductCostTouristDataReq.getTouristTypeId());
                touristNames.append("," + airProductCostTouristDataReq.getTouristTypeName());
                AirProductCostTourist airProductCostTourist = EntityUtil.copy(airProductCostTouristDataReq, AirProductCostTourist.class);
                airProductCostTourist.setCostId(airProductCostId);
                airProductCostTourist.setCreateId(tokenUser.getId());
                airProductCostTourist.setGmtCreate(LocalDateTime.now());
                airProductCostTourist.setModifiedId(tokenUser.getId());
                airProductCostTourist.setGmtModified(LocalDateTime.now());
                Long airProductCostTouristId = IdWorker.getId();
                airProductCostTourist.setId(airProductCostTouristId);
                airProductCostTouristMapper.insert(airProductCostTourist);
                List<AirProductCostTaxationReq> airProductCostTaxationReqList = airProductCostTouristDataReq.getAirProductCostTaxationReqList();
                if (CollectionUtil.isEmpty(airProductCostTaxationReqList)) {
                    throw new BusinessException(SystemError.AIR_PRODUCT_12018, airProductCostTouristDataReq.getTouristTypeName());
                }
                for (AirProductCostTaxationReq airProductCostTaxationReq : airProductCostTaxationReqList) {
                    if (null == airProductCostTaxationReq.getAmount()) {
                        throw new BusinessException(SystemError.AIR_PRODUCT_12019, airProductCostTouristDataReq.getTouristTypeName(), airProductCostTaxationReq.getTaxationName());
                    }
                    AirProductCostTaxation airProductCostTaxation = EntityUtil.copy(airProductCostTaxationReq, AirProductCostTaxation.class);
                    airProductCostTaxation.setTouristId(airProductCostTouristId);
                    airProductCostTaxation.setCreateId(tokenUser.getId());
                    airProductCostTaxation.setIsDeleted(IsDeletedCode.NO.getCode());
                    airProductCostTaxation.setGmtCreate(LocalDateTime.now());
                    airProductCostTaxation.setModifiedId(tokenUser.getId());
                    airProductCostTaxation.setGmtModified(LocalDateTime.now());
                    airProductCostTaxation.setId(IdWorker.getId());
                    airProductCostTaxation.setProductId(airProductId);
                    airProductCostTaxationMapper.insert(airProductCostTaxation);
                }
            }
            airProductCost.setTouristTypeId(touristIds.substring(1));
            airProductCost.setTouristTypeName(touristNames.substring(1));
            airProductCostMapper.insert(airProductCost);
        }
        return Result.success(airProductId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result editSetapi(List<AirProductApiReq> airProductApiReqList, TokenUser tokenUser) {
        Set<Long> airProductIds = Sets.newHashSet();
        Map<Long, AirProductApiReq> airProductApiReqMap = Maps.newHashMap();
        for (AirProductApiReq airProductApiReq : airProductApiReqList) {
            airProductIds.add(airProductApiReq.getId());
            airProductApiReqMap.put(airProductApiReq.getId(), airProductApiReq);
        }
        QueryWrapper<AirProduct> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.lambda().in(AirProduct::getId, airProductIds);
        List<AirProduct> productList = baseMapper.selectList(productQueryWrapper);
        if (CollectionUtils.isEmpty(productList)) {
            return Result.success(SystemError.AIR_PRODUCT_12004);
        }
        for (AirProduct airProduct : productList) {
            UpdateWrapper<AirProduct> updateWrapper = new UpdateWrapper<>();
            AirProductApiReq airProductApiReq = airProductApiReqMap.get(airProduct.getId());
            updateWrapper.lambda().eq(AirProduct::getId, airProduct.getId());
            updateWrapper.lambda().set(ObjectUtils.isNotEmpty(airProductApiReq.getPackStatus()), AirProduct::getPackStatus, airProductApiReq.getPackStatus());
            updateWrapper.lambda().set(ObjectUtils.isNotEmpty(airProductApiReq.getSellStatus()), AirProduct::getSellStatus, airProductApiReq.getSellStatus());
            updateWrapper.lambda().set(AirProduct::getModifiedId, tokenUser.getId());
            updateWrapper.lambda().set(AirProduct::getGmtModified, LocalDateTime.now());
            baseMapper.update(null, updateWrapper);
            UpdateWrapper<AirProductReservationSettings> settingsUpdateWrapper = new UpdateWrapper<>();
            if (ObjectUtils.isNotEmpty(airProductApiReq.getRefundFeePrice()) || ObjectUtils.isNotEmpty(airProductApiReq.getServiceChargePrice())) {
                settingsUpdateWrapper.lambda().eq(AirProductReservationSettings::getAirProductId, airProduct.getId());
                settingsUpdateWrapper.lambda().set(AirProductReservationSettings::getModifiedId, tokenUser.getId());
                settingsUpdateWrapper.lambda().set(AirProductReservationSettings::getGmtModified, LocalDateTime.now());
                settingsUpdateWrapper.lambda().set(ObjectUtils.isNotEmpty(airProductApiReq.getRefundFeePrice()), AirProductReservationSettings::getRefundFeePrice,
                        airProductApiReq.getRefundFeePrice());
                settingsUpdateWrapper.lambda().set(ObjectUtils.isNotEmpty(airProductApiReq.getServiceChargePrice()), AirProductReservationSettings::getServiceChargePrice,
                        airProductApiReq.getServiceChargePrice());
                airProductReservationSettingsMapper.update(null, settingsUpdateWrapper);
            }
        }
        return Result.success();
    }

    @Override
    public Result editStatus(AirProductStatusReq req, TokenUser tokenUser) {
        AirProduct airProduct = baseMapper.selectById(req.getId());
        if (null == airProduct) {
            return Result.failed(SystemError.AIR_PRODUCT_12004);
        }
        UpdateWrapper<AirProduct> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(AirProduct::getId, req.getId());
        /**修改审批状态*/
        if (null != req.getApprovalStatus()) {
            //修改状态
            if (NumberConstant.ONE.getValue().equals(airProduct.getApprovalStatus())) {
                updateWrapper.lambda().set(AirProduct::getApprovalStatus, 2);
                //提交审核
                productAudit(req.getId(), tokenUser);
            } else if (NumberConstant.TWO.getValue().equals(airProduct.getApprovalStatus())) {
                updateWrapper.lambda().set(AirProduct::getApprovalStatus, 1);
            }
        }
        /**是否推荐*/
        if (null != req.getRecommendStatus() && req.getRecommendStatus().intValue() == NumberConstant.ONE.getValue()) {
            if (NumberConstant.ONE.getValue().intValue() == airProduct.getRecommendStatus().intValue()) {
                updateWrapper.lambda().set(AirProduct::getRecommendStatus, 0);
            } else {
                updateWrapper.lambda().set(AirProduct::getRecommendStatus, 1);
            }
        }
        /**修改售卖状态*/
        if (null != req.getSellStatus() && req.getSellStatus().intValue() == NumberConstant.ONE.getValue()) {
            if (NumberConstant.ONE.getValue().intValue() == airProduct.getSellStatus().intValue()) {
                updateWrapper.lambda().set(AirProduct::getSellStatus, 0);
            } else {
                if (airProduct.getApprovalStatus().intValue() != 5) {
                    return Result.failed(SystemError.AIR_PRODUCT_12006);
                }
                updateWrapper.lambda().set(AirProduct::getSellStatus, 1);
            }
        }
        updateWrapper.lambda().set(AirProduct::getModifiedId, tokenUser.getId());
        updateWrapper.lambda().set(AirProduct::getGmtModified, LocalDateTime.now());
        baseMapper.update(null, updateWrapper);
        return Result.success(req.getId());
    }

    /**
     * 产品审核
     *
     * @param productId
     * @param tokenUser
     */
    private void productAudit(Long productId, TokenUser tokenUser) {
        //提交审批
        Result<ApprovalStartDTO> result = iSysApprovalService.start(SystemBusinessType.AIR_TICKET.getCode(),
                SysApprovalType.ADD_AIR.getCode(),
                productId, tokenUser.getId(), null, null);
        Assert.isTrue(result.isSuccess(), SystemError.getDefined(result.getCode()));
    }

    @Override
    public Result<PageResponse<AirProductListDTO>> list(AirProductListReq req) {

        Page<AirProductListDTO> page = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<AirProductListDTO> productListQueryWrapper = new QueryWrapper<>();
        if (CollectionUtil.isNotEmpty(req.getProductIds())) {
            productListQueryWrapper.in("tp.id", req.getProductIds());
        } else {
            productListQueryWrapper.eq(ObjectUtils.isNotEmpty(req.getCompanyId()), "tf.company_id", req.getCompanyId());
            productListQueryWrapper.like(StringUtils.isNotBlank(req.getFlightNumber()), "tf.flight_number", req.getFlightNumber());
            productListQueryWrapper.eq(ObjectUtils.isNotEmpty(req.getDepCityId()), "tf.dep_city_id", req.getDepCityId());
            productListQueryWrapper.eq(ObjectUtils.isNotEmpty(req.getArrCityId()), "tf.arr_city_id", req.getArrCityId());
            productListQueryWrapper.like(StringUtils.isNotEmpty(req.getDepAirportId()), "tf.dep_airport_id", req.getDepAirportId());
            productListQueryWrapper.eq(StringUtils.isNotEmpty(req.getArrAirportId()), "tf.dep_airport_id", req.getArrAirportId());
            AirProductListReq.FlightTime depTime = req.getDepTime();
            if (null != depTime) {
                productListQueryWrapper.ge(ObjectUtils.isNotEmpty(depTime.getStar()), "tf.dep_time", depTime.getStar());
                productListQueryWrapper.le(ObjectUtils.isNotEmpty(depTime.getEnd()), "tf.arr_time", depTime.getEnd());
            }
            productListQueryWrapper.eq(ObjectUtils.isNotEmpty(req.getCabinClass()), "tp.cabin_class", req.getCabinClass());
            productListQueryWrapper.eq(ObjectUtils.isNotEmpty(req.getSupplierId()), "tp.supplier_id", req.getSupplierId());
            productListQueryWrapper.like(ObjectUtils.isNotEmpty(req.getCode()), "tp.code", req.getCode());
            productListQueryWrapper.eq(ObjectUtils.isNotEmpty(req.getSource()), "tp.source", req.getSource());
            productListQueryWrapper.eq(ObjectUtils.isNotEmpty(req.getSellStatus()), "tp.sell_status", req.getSellStatus());
            productListQueryWrapper.eq(ObjectUtils.isNotEmpty(req.getApprovalStatus()), "tp.approval_status", req.getApprovalStatus());
            productListQueryWrapper.eq(ObjectUtils.isNotEmpty(req.getPackStatus()), "tp.pack_status", req.getPackStatus());
            productListQueryWrapper.eq(ObjectUtils.isNotEmpty(req.getRecommendStatus()), "tp.recommend_status", req.getRecommendStatus());
        }

        Page<AirProductListDTO> iPage = airProductMapper.queryProcutList(page, productListQueryWrapper);
        List<AirProductListDTO> airProductListDtoList = iPage.getRecords();
        if (CollectionUtil.isEmpty(airProductListDtoList)) {
            return Result.success(new PageResponse<AirProductListDTO>(new ArrayList<>(), true, true, 0l, 1l, req.getPageSize().longValue()));
        }
        for (AirProductListDTO airProductListDto : airProductListDtoList) {
            airProductListDto.setChargeUserName("測試默認寫死");
            //airProductListDto.setChargeUserName(iSysUserService.queryCacheUser(airProductListDto.getChargeUserId()).getCnName());
        }
        return Result.success(new PageResponse<AirProductListDTO>(airProductListDtoList, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                iPage.getTotal(), iPage.getCurrent(), iPage.getSize()));
    }


    @Override
    @Transactional
    public Result updateStrategy(AirProductSaleStrategyUpdateReq req, TokenUser tokenUser) {
        Long userId = tokenUser.getId();
        /**验证是否传入了产品Id */
        List<Long> airProductIds = req.getAirProductIds();
        if (CollectionUtils.isEmpty(airProductIds)) {
            return Result.failed(SystemError.AIR_PRODUCT_12004);
        }
        /** 验证时间段 是否重复*/
        /**localDateSet 去除重复日期 localDateSize未去除重复日期时的日期总笔 如果两者不相等 则存在重复日期*/
        Set<LocalDate> localDateSet = Sets.newHashSet();
        int localDateSize = 0;
        List<AirProductSaleStrategyData> airProductSaleStrategyReqList = req.getAirProductSaleStrategyReqList();
        if (CollectionUtil.isEmpty(airProductSaleStrategyReqList)) {
            return Result.failed(SystemError.AIR_PRODUCT_12007);
        }
        for (AirProductSaleStrategyData airProductSaleStrategyReq : airProductSaleStrategyReqList) {
            List<AirProductStrategyTimeData> airProductStrategyTimeReqList = airProductSaleStrategyReq.getAirProductStrategyTimeData();
            if (CollectionUtil.isEmpty(airProductStrategyTimeReqList)) {
                throw new BusinessException(SystemError.AIR_PRODUCT_12008);
            }
            for (AirProductStrategyTimeData airProductStrategyTimeReq : airProductStrategyTimeReqList) {
                LocalDate dateBegin = airProductStrategyTimeReq.getStart();
                LocalDate dateEnd = airProductStrategyTimeReq.getEnd();
                List<LocalDate> dates = Stream.iterate(dateBegin, date -> date.plusDays(1))
                        .limit(ChronoUnit.DAYS.between(dateBegin, dateEnd))
                        .collect(Collectors.toList());
                localDateSet.addAll(dates);
                localDateSize += dates.size();
            }
        }
        if (localDateSet.size() != localDateSize) {
            return Result.failed(SystemError.AIR_PRODUCT_12002);
        }
        /**所有验证通过--先清空历史数据 直接保存新的数据*/
        deleteAirProductStrate(airProductIds);
        /**开始保存新的数据*/
        boolean isRollBack = true;
        for (Long airProductId : airProductIds) {
            for (AirProductSaleStrategyData airProductSaleStrategyReq : airProductSaleStrategyReqList) {
                /**创建策略成本主体信息*/
                AirProductSaleStrategy airProductSaleStrategy = new AirProductSaleStrategy();
                Long airProductSaleStrategyId = IdWorker.getId();
                airProductSaleStrategy.setId(airProductSaleStrategyId);
                airProductSaleStrategy.setName(airProductSaleStrategyReq.getName());
                airProductSaleStrategy.setCreateId(userId);
                airProductSaleStrategy.setGmtCreate(LocalDateTime.now());
                airProductSaleStrategy.setModifiedId(userId);
                airProductSaleStrategy.setGmtModified(LocalDateTime.now());
                airProductSaleStrategy.setIsDeleted(IsDeletedCode.NO.getCode());
                airProductSaleStrategy.setProductId(airProductId);
                airProductSaleStrategyMapper.insert(airProductSaleStrategy);
                /**创建策略时间段*/
                List<AirProductStrategyTimeData> airProductStrategyTimeReqList = airProductSaleStrategyReq.getAirProductStrategyTimeData();
                for (AirProductStrategyTimeData airProductStrategyTimeReq : airProductStrategyTimeReqList) {
                    AirProductSaleStrategyVaildDate airProductSaleStrategyVaildDate = new AirProductSaleStrategyVaildDate();
                    Long airProductSaleStrategyVaildDateId = IdWorker.getId();
                    airProductSaleStrategyVaildDate.setId(airProductSaleStrategyVaildDateId);
                    airProductSaleStrategyVaildDate.setCreateId(userId);
                    airProductSaleStrategyVaildDate.setGmtCreate(LocalDateTime.now());
                    airProductSaleStrategyVaildDate.setModifiedId(userId);
                    airProductSaleStrategyVaildDate.setGmtModified(LocalDateTime.now());
                    airProductSaleStrategyVaildDate.setProductId(airProductId);
                    airProductSaleStrategyVaildDate.setTimeBegin(airProductStrategyTimeReq.getStart());
                    airProductSaleStrategyVaildDate.setTimeEnd(airProductStrategyTimeReq.getEnd());
                    airProductSaleStrategyVaildDate.setStrategyId(airProductSaleStrategyId);
                    airProductSaleStrategyVaildDateMapper.insert(airProductSaleStrategyVaildDate);
                }
                /**线下自营*/
                AirProductChannelofflineSelfData airProductChannelofflineSelfReq = airProductSaleStrategyReq.getAirProductChannelofflineSelfData();
                if (null != airProductChannelofflineSelfReq && null != airProductChannelofflineSelfReq.getVisableType()) {
                    isRollBack = false;
                    AirProductChannelOffline airProductChannelOfflineSelf = new AirProductChannelOffline();
                    Long airProductChannelOfflineSelfId = IdWorker.getId();
                    airProductChannelOfflineSelf.setChannelType(1);
                    airProductChannelOfflineSelf.setVisableType(airProductChannelofflineSelfReq.getVisableType());
                    airProductChannelOfflineSelf.setId(airProductChannelOfflineSelfId);
                    airProductChannelOfflineSelf.setCreateId(userId);
                    airProductChannelOfflineSelf.setGmtCreate(LocalDateTime.now());
                    airProductChannelOfflineSelf.setModifiedId(userId);
                    airProductChannelOfflineSelf.setGmtModified(LocalDateTime.now());
                    airProductChannelOfflineSelf.setProductId(airProductId);
                    airProductChannelOfflineSelf.setStrategyId(airProductSaleStrategyId);
                    airProductChannelOfflineMapper.insert(airProductChannelOfflineSelf);
                    if (airProductChannelOfflineSelf.getVisableType().intValue() != 1) {
                        List<AirProductOfflineCustomData> airProductOfflineCusReqList = airProductChannelofflineSelfReq.getAirProductOfflineCustomDataList();
                        if (CollectionUtils.isNotEmpty(airProductOfflineCusReqList)) {
                            for (AirProductOfflineCustomData airProductOfflineCusReq : airProductOfflineCusReqList) {
                                AirProductSaleStrategyDataInfoData airProductStrategyDataReq = airProductOfflineCusReq.getAirProductSaleStrategyDataInfoData();
                                AirProductUtil.validStrategyInfo(airProductStrategyDataReq);
                                AirProductChannelOfflineSelfCustom airProductChannelOfflineSelfCustom = EntityUtil.copy(airProductStrategyDataReq,
                                        AirProductChannelOfflineSelfCustom.class);
                                airProductChannelOfflineSelfCustom.setId(IdWorker.getId());
                                airProductChannelOfflineSelfCustom.setCreateId(userId);
                                airProductChannelOfflineSelfCustom.setGmtCreate(LocalDateTime.now());
                                airProductChannelOfflineSelfCustom.setModifiedId(userId);
                                airProductChannelOfflineSelfCustom.setGmtModified(LocalDateTime.now());
                                airProductChannelOfflineSelfCustom.setProductId(airProductId);
                                airProductChannelOfflineSelfCustom.setOfflineId(airProductChannelOfflineSelfId);
                                if (airProductChannelofflineSelfReq.getVisableType().intValue() == 3) {
                                    airProductChannelOfflineSelfCustom.setRelationId(airProductOfflineCusReq.getRelationId());
                                    airProductChannelOfflineSelfCustom.setName(airProductOfflineCusReq.getName());
                                    if (null == airProductOfflineCusReq.getCheckType()) {
                                        new BusinessException(SystemError.SYS_402);
                                    }
                                    airProductChannelOfflineSelfCustom.setCheckType(airProductOfflineCusReq.getCheckType());
                                }
                                airProductChannelOfflineSelfCustomMapper.insert(airProductChannelOfflineSelfCustom);
                            }
                        } else {
                            new BusinessException(SystemError.AIR_PRODUCT_12009);
                        }
                    }
                }
                /**线下代理商*/
                AirProductChannelOfflineAgentData airProductChannelOfflineAgentReq = airProductSaleStrategyReq.getAirProductChannelOfflineAgentData();
                if (null != airProductChannelOfflineAgentReq && null != airProductChannelOfflineAgentReq.getVisableType()) {
                    isRollBack = false;
                    AirProductChannelOffline airProductChannelOfflineAgent = new AirProductChannelOffline();
                    Long airProductChannelOfflineAgentId = IdWorker.getId();
                    airProductChannelOfflineAgent.setChannelType(2);
                    airProductChannelOfflineAgent.setVisableType(airProductChannelOfflineAgentReq.getVisableType());
                    airProductChannelOfflineAgent.setId(airProductChannelOfflineAgentId);
                    airProductChannelOfflineAgent.setCreateId(userId);
                    airProductChannelOfflineAgent.setGmtCreate(LocalDateTime.now());
                    airProductChannelOfflineAgent.setModifiedId(userId);
                    airProductChannelOfflineAgent.setGmtModified(LocalDateTime.now());
                    airProductChannelOfflineAgent.setProductId(airProductId);
                    airProductChannelOfflineAgent.setStrategyId(airProductSaleStrategyId);
                    airProductChannelOfflineMapper.insert(airProductChannelOfflineAgent);
                    if (airProductChannelOfflineAgent.getVisableType().intValue() != 1) {
                        List<AirProductOfflineCustomData> airProductOfflineCusAgentReqList = airProductChannelOfflineAgentReq.getAirProductOfflineCustomData();
                        if (CollectionUtils.isNotEmpty(airProductOfflineCusAgentReqList)) {
                            for (AirProductOfflineCustomData airProductOfflineCusReq : airProductOfflineCusAgentReqList) {
                                AirProductSaleStrategyDataInfoData airProductStrategyDataReq = airProductOfflineCusReq.getAirProductSaleStrategyDataInfoData();
                                AirProductUtil.validStrategyInfo(airProductStrategyDataReq);
                                AirProductChannelOfflineAgentCustom airProductChannelOfflineAgentCustom = EntityUtil.copy(airProductStrategyDataReq,
                                        AirProductChannelOfflineAgentCustom.class);
                                airProductChannelOfflineAgentCustom.setId(IdWorker.getId());
                                airProductChannelOfflineAgentCustom.setCreateId(userId);
                                airProductChannelOfflineAgentCustom.setGmtCreate(LocalDateTime.now());
                                airProductChannelOfflineAgentCustom.setModifiedId(userId);
                                airProductChannelOfflineAgentCustom.setGmtModified(LocalDateTime.now());
                                airProductChannelOfflineAgentCustom.setProductId(airProductId);
                                airProductChannelOfflineAgentCustom.setOfflineId(airProductChannelOfflineAgentId);
                                if (airProductChannelofflineSelfReq.getVisableType().intValue() == 3) {
                                    airProductChannelOfflineAgentCustom.setAgentId(airProductOfflineCusReq.getRelationId());
                                    airProductChannelOfflineAgentCustom.setAgentName(airProductOfflineCusReq.getName());
                                }
                                int insert = airProductChannelOfflineAgentCustomMapper.insert(airProductChannelOfflineAgentCustom);
                            }
                        } else {
                            throw new BusinessException(SystemError.AIR_PRODUCT_12010);
                        }
                    }
                }
                /**线上官方平台*/
                List<AirProductOnlineSelfPlatformData> airProductOnlineSelfPlatformReqList = airProductSaleStrategyReq.getAirProductOnlineSelfPlatformDataList();
                if (CollectionUtils.isNotEmpty(airProductOnlineSelfPlatformReqList)) {
                    isRollBack = false;
                    for (AirProductOnlineSelfPlatformData airProductOnlineSelfPlatformReq : airProductOnlineSelfPlatformReqList) {
                        AirProductSaleStrategyDataInfoData airProductStrategyDataReq = airProductOnlineSelfPlatformReq.getAirProductSaleStrategyDataInfoData();
                        AirProductUtil.validStrategyInfo(airProductStrategyDataReq);
                        AirProductChannelOnlineSelfPlatform airProductChannelOnlineSelfPlatform = EntityUtil.copy(airProductStrategyDataReq,
                                AirProductChannelOnlineSelfPlatform.class);
                        airProductChannelOnlineSelfPlatform.setId(IdWorker.getId());
                        airProductChannelOnlineSelfPlatform.setCreateId(userId);
                        airProductChannelOnlineSelfPlatform.setGmtCreate(LocalDateTime.now());
                        airProductChannelOnlineSelfPlatform.setModifiedId(userId);
                        airProductChannelOnlineSelfPlatform.setGmtModified(LocalDateTime.now());
                        airProductChannelOnlineSelfPlatform.setProductId(airProductId);
                        airProductChannelOnlineSelfPlatform.setStrategyId(airProductSaleStrategyId);
                        airProductChannelOnlineSelfPlatform.setChannelId(airProductOnlineSelfPlatformReq.getChannelId());
                        airProductChannelOnlineSelfPlatform.setChannelName(airProductOnlineSelfPlatformReq.getChannelName());
                        airProductChannelOnlineSelfPlatformMapper.insert(airProductChannelOnlineSelfPlatform);
                    }
                }
                /**线上第三方平台*/
                List<AirProductOnlineThirdPlatformData> airProductOnlineThirdPlatformReqList = airProductSaleStrategyReq.getAirProductOnlineThirdPlatformDataList();
                if (CollectionUtils.isNotEmpty(airProductOnlineThirdPlatformReqList)) {
                    isRollBack = false;
                    for (AirProductOnlineThirdPlatformData airProductOnlineThirdPlatformReq : airProductOnlineThirdPlatformReqList) {
                        AirProductSaleStrategyDataInfoData airProductStrategyDataReq = airProductOnlineThirdPlatformReq.getAirProductSaleStrategyDataInfoData();
                        AirProductUtil.validStrategyInfo(airProductStrategyDataReq);
                        AirProductChannelOnlineThirdPlatform airProductChannelOnlineThirdPlatform = EntityUtil.copy(airProductStrategyDataReq,
                                AirProductChannelOnlineThirdPlatform.class);
                        airProductChannelOnlineThirdPlatform.setId(IdWorker.getId());
                        airProductChannelOnlineThirdPlatform.setCreateId(userId);
                        airProductChannelOnlineThirdPlatform.setGmtCreate(LocalDateTime.now());
                        airProductChannelOnlineThirdPlatform.setModifiedId(userId);
                        airProductChannelOnlineThirdPlatform.setGmtModified(LocalDateTime.now());
                        airProductChannelOnlineThirdPlatform.setProductId(airProductId);
                        airProductChannelOnlineThirdPlatform.setStrategyId(airProductSaleStrategyId);
                        airProductChannelOnlineThirdPlatform.setPlatformId(airProductOnlineThirdPlatformReq.getPlatformId());
                        airProductChannelOnlineThirdPlatform.setPlatformName(airProductOnlineThirdPlatformReq.getPlatformName());
                        airProductChannelOnlineThirdPlatformMapper.insert(airProductChannelOnlineThirdPlatform);
                    }
                }
            }
        }
        if (isRollBack) {
            throw new BusinessException(SystemError.AIR_PRODUCT_12007);
        }
        return Result.success();
    }

    @Override
    public Result<AirProductSaleStrategyDTO> queryStrategy(Long id) {
        /**查询产品信息*/
        AirProduct airProduct = baseMapper.selectById(id);
        if (null == airProduct) {
            return Result.failed(SystemError.AIR_PRODUCT_12004);
        }
        AirProductSaleStrategyDTO airProductSaleStrategyDto = new AirProductSaleStrategyDTO();
        airProductSaleStrategyDto.setId(id);
        /**查询所有的策略*/
        QueryWrapper<AirProductSaleStrategy> saleStrategyQueryWrapper = new QueryWrapper<>();
        saleStrategyQueryWrapper.lambda().eq(AirProductSaleStrategy::getProductId, id);
        List<AirProductSaleStrategy> airProductSaleStrategyList = airProductSaleStrategyMapper.selectList(saleStrategyQueryWrapper);
        /**查询所有的时间段*/
        QueryWrapper<AirProductSaleStrategyVaildDate> saleStrategyVaildDateQueryWrapper = new QueryWrapper<>();
        saleStrategyVaildDateQueryWrapper.lambda().eq(AirProductSaleStrategyVaildDate::getProductId, id);
        List<AirProductSaleStrategyVaildDate> airProductSaleStrategyVaildDateList = airProductSaleStrategyVaildDateMapper.selectList(saleStrategyVaildDateQueryWrapper);
        Map<Long, List<AirProductSaleStrategyVaildDate>> vaildDateMap = Maps.newHashMap();
        for (AirProductSaleStrategyVaildDate airProductSaleStrategyVaildDate : airProductSaleStrategyVaildDateList) {
            List<AirProductSaleStrategyVaildDate> mapValue = vaildDateMap.get(airProductSaleStrategyVaildDate.getStrategyId());
            if (mapValue == null) {
                mapValue = Lists.newArrayList();
            }
            mapValue.add(airProductSaleStrategyVaildDate);
            vaildDateMap.put(airProductSaleStrategyVaildDate.getStrategyId(), mapValue);
        }
        /**查询线下渠道*/
        QueryWrapper<AirProductChannelOffline> channelOfflineQueryWrapper = new QueryWrapper<>();
        channelOfflineQueryWrapper.lambda().eq(AirProductChannelOffline::getProductId, id);
        List<AirProductChannelOffline> airProductChannelOfflineList = airProductChannelOfflineMapper.selectList(channelOfflineQueryWrapper);
        Map<Long, List<AirProductChannelOffline>> offlineMap = Maps.newHashMap();
        for (AirProductChannelOffline airProductChannelOffline : airProductChannelOfflineList) {
            List<AirProductChannelOffline> mapVlaue = offlineMap.get(airProductChannelOffline.getStrategyId());
            if (mapVlaue == null) {
                mapVlaue = Lists.newArrayList();
            }
            mapVlaue.add(airProductChannelOffline);
            offlineMap.put(airProductChannelOffline.getStrategyId(), mapVlaue);
        }

        /**代理商*/
        QueryWrapper<AirProductChannelOfflineAgentCustom> channelOfflineAgentCustomQueryWrapper = new QueryWrapper<>();
        channelOfflineAgentCustomQueryWrapper.lambda().eq(AirProductChannelOfflineAgentCustom::getProductId, id);
        List<AirProductChannelOfflineAgentCustom> airProductChannelOfflineAgentCustomList =
                airProductChannelOfflineAgentCustomMapper.selectList(channelOfflineAgentCustomQueryWrapper);
        Map<Long, List<AirProductChannelOfflineAgentCustom>> agentCustomMap = Maps.newHashMap();
        for (AirProductChannelOfflineAgentCustom airProductChannelOfflineAgentCustom : airProductChannelOfflineAgentCustomList) {
            List<AirProductChannelOfflineAgentCustom> mapVlaue = agentCustomMap.get(airProductChannelOfflineAgentCustom.getOfflineId());
            if (mapVlaue == null) {
                mapVlaue = Lists.newArrayList();
            }
            mapVlaue.add(airProductChannelOfflineAgentCustom);
            agentCustomMap.put(airProductChannelOfflineAgentCustom.getOfflineId(), mapVlaue);
        }

        /**自营*/
        QueryWrapper<AirProductChannelOfflineSelfCustom> channelOfflineSelfCustomQueryWrapper = new QueryWrapper<>();
        channelOfflineSelfCustomQueryWrapper.lambda().eq(AirProductChannelOfflineSelfCustom::getProductId, id);
        List<AirProductChannelOfflineSelfCustom> airProductChannelOfflineSelfCustomList = airProductChannelOfflineSelfCustomMapper.selectList(channelOfflineSelfCustomQueryWrapper);
        Map<Long, List<AirProductChannelOfflineSelfCustom>> selfCustomMap = Maps.newHashMap();
        for (AirProductChannelOfflineSelfCustom airProductChannelOfflineSelfCustom : airProductChannelOfflineSelfCustomList) {
            List<AirProductChannelOfflineSelfCustom> mapVlaue = selfCustomMap.get(airProductChannelOfflineSelfCustom.getOfflineId());
            if (mapVlaue == null) {
                mapVlaue = Lists.newArrayList();
            }
            mapVlaue.add(airProductChannelOfflineSelfCustom);
            selfCustomMap.put(airProductChannelOfflineSelfCustom.getOfflineId(), mapVlaue);
        }


        /**查询所有的线上官方渠道*/
        QueryWrapper<AirProductChannelOnlineSelfPlatform> onlineSelfPlatformQueryWrapper = new QueryWrapper<>();
        onlineSelfPlatformQueryWrapper.lambda().eq(AirProductChannelOnlineSelfPlatform::getProductId, id);
        List<AirProductChannelOnlineSelfPlatform> airProductChannelOnlineSelfPlatformList = airProductChannelOnlineSelfPlatformMapper.selectList(onlineSelfPlatformQueryWrapper);
        Map<Long, List<AirProductChannelOnlineSelfPlatform>> selfPlatformMap = Maps.newHashMap();
        for (AirProductChannelOnlineSelfPlatform airProductChannelOnlineSelfPlatform : airProductChannelOnlineSelfPlatformList) {
            List<AirProductChannelOnlineSelfPlatform> mapVlaue = selfPlatformMap.get(airProductChannelOnlineSelfPlatform.getStrategyId());
            if (mapVlaue == null) {
                mapVlaue = Lists.newArrayList();
            }
            mapVlaue.add(airProductChannelOnlineSelfPlatform);
            selfPlatformMap.put(airProductChannelOnlineSelfPlatform.getStrategyId(), mapVlaue);
        }
        /**查询所有的线上第三方渠道*/
        QueryWrapper<AirProductChannelOnlineThirdPlatform> onlineThirdPlatformQueryWrapper = new QueryWrapper<>();
        onlineThirdPlatformQueryWrapper.lambda().eq(AirProductChannelOnlineThirdPlatform::getProductId, id);
        List<AirProductChannelOnlineThirdPlatform> airProductChannelOnlineThirdPlatformList =
                airProductChannelOnlineThirdPlatformMapper.selectList(onlineThirdPlatformQueryWrapper);
        Map<Long, List<AirProductChannelOnlineThirdPlatform>> thirdPlatformMap = Maps.newHashMap();
        for (AirProductChannelOnlineThirdPlatform airProductChannelOnlineThirdPlatform : airProductChannelOnlineThirdPlatformList) {
            List<AirProductChannelOnlineThirdPlatform> mapVlaue = thirdPlatformMap.get(airProductChannelOnlineThirdPlatform.getStrategyId());
            if (mapVlaue == null) {
                mapVlaue = Lists.newArrayList();
            }
            mapVlaue.add(airProductChannelOnlineThirdPlatform);
            thirdPlatformMap.put(airProductChannelOnlineThirdPlatform.getStrategyId(), mapVlaue);
        }
        /**开始组装返回结果*/
        List<AirProductSaleStrategyData> airProductSaleStrategyDataList = Lists.newArrayList();
        for (AirProductSaleStrategy airProductSaleStrategy : airProductSaleStrategyList) {
            AirProductSaleStrategyData airProductSaleStrategyData = new AirProductSaleStrategyData();
            airProductSaleStrategyData.setName(airProductSaleStrategy.getName());
            /**组装时间段*/
            List<AirProductSaleStrategyVaildDate> airProductSaleStrategyVaildDates = vaildDateMap.get(airProductSaleStrategy.getId());
            List<AirProductStrategyTimeData> airProductStrategyTimeDataList = Lists.newArrayList();
            for (AirProductSaleStrategyVaildDate airProductSaleStrategyVaildDate : airProductSaleStrategyVaildDates) {
                AirProductStrategyTimeData airProductStrategyTimeData = new AirProductStrategyTimeData();
                airProductStrategyTimeData.setStart(airProductSaleStrategyVaildDate.getTimeBegin());
                airProductStrategyTimeData.setEnd(airProductSaleStrategyVaildDate.getTimeEnd());
                airProductStrategyTimeDataList.add(airProductStrategyTimeData);
            }
            airProductSaleStrategyData.setAirProductStrategyTimeData(airProductStrategyTimeDataList);
            List<AirProductChannelOffline> airProductChannelOfflines = offlineMap.get(airProductSaleStrategy.getId());
            /**组装线下渠道*/
            AirProductChannelofflineSelfData airProductChannelofflineSelfData = new AirProductChannelofflineSelfData();
            AirProductChannelOfflineAgentData airProductChannelOfflineAgentData = new AirProductChannelOfflineAgentData();
            for (AirProductChannelOffline airProductChannelOffline : airProductChannelOfflines) {
                if (airProductChannelOffline.getChannelType().intValue() == 1) {
                    airProductChannelofflineSelfData.setVisableType(airProductChannelOffline.getVisableType());
                    if (airProductChannelOffline.getVisableType().intValue() != 1) {
                        List<AirProductChannelOfflineSelfCustom> airProductChannelOfflineSelfCustoms = selfCustomMap.get(airProductChannelOffline.getId());
                        List<AirProductOfflineCustomData> airProductOfflineCustomDataList = Lists.newArrayList();
                        for (AirProductChannelOfflineSelfCustom airProductChannelOfflineSelfCustom : airProductChannelOfflineSelfCustoms) {
                            AirProductOfflineCustomData airProductOfflineCustomData = new AirProductOfflineCustomData();
                            airProductOfflineCustomData.setRelationId(airProductChannelOfflineSelfCustom.getRelationId());
                            airProductOfflineCustomData.setName(airProductChannelOfflineSelfCustom.getName());
                            airProductOfflineCustomData.setCheckType(airProductChannelOfflineSelfCustom.getCheckType());
                            AirProductSaleStrategyDataInfoData airProductSaleStrategyDataInfoData = EntityUtil.copy(airProductChannelOfflineSelfCustom,
                                    AirProductSaleStrategyDataInfoData.class);
                            airProductOfflineCustomData.setAirProductSaleStrategyDataInfoData(airProductSaleStrategyDataInfoData);
                            airProductOfflineCustomDataList.add(airProductOfflineCustomData);
                        }
                        airProductChannelofflineSelfData.setAirProductOfflineCustomDataList(airProductOfflineCustomDataList);
                    }
                } else {
                    airProductChannelOfflineAgentData.setVisableType(airProductChannelOffline.getVisableType());
                    if (airProductChannelOffline.getVisableType().intValue() != 1) {
                        List<AirProductChannelOfflineAgentCustom> airProductChannelOfflineAgentCustoms = agentCustomMap.get(airProductChannelOffline.getId());
                        List<AirProductOfflineCustomData> airProductOfflineCustomDataList = Lists.newArrayList();
                        for (AirProductChannelOfflineAgentCustom airProductChannelOfflineSelfCustom : airProductChannelOfflineAgentCustoms) {
                            AirProductOfflineCustomData airProductOfflineCustomData = new AirProductOfflineCustomData();
                            airProductOfflineCustomData.setRelationId(airProductChannelOfflineSelfCustom.getAgentId());
                            airProductOfflineCustomData.setName(airProductChannelOfflineSelfCustom.getAgentName());
                            airProductOfflineCustomData.setCheckType(null);
                            AirProductSaleStrategyDataInfoData airProductSaleStrategyDataInfoData = EntityUtil.copy(airProductChannelOfflineSelfCustom,
                                    AirProductSaleStrategyDataInfoData.class);
                            airProductOfflineCustomData.setAirProductSaleStrategyDataInfoData(airProductSaleStrategyDataInfoData);
                            airProductOfflineCustomDataList.add(airProductOfflineCustomData);
                        }
                        airProductChannelOfflineAgentData.setAirProductOfflineCustomData(airProductOfflineCustomDataList);
                    }
                }
            }
            /**祖装线上官方平台数据*/
            List<AirProductOnlineSelfPlatformData> airProductOnlineSelfPlatformDataList = Lists.newArrayList();
            List<AirProductChannelOnlineSelfPlatform> airProductChannelOnlineSelfPlatforms = selfPlatformMap.get(airProductSaleStrategy.getId());
            if (CollectionUtil.isNotEmpty(airProductChannelOnlineSelfPlatforms)) {
                for (AirProductChannelOnlineSelfPlatform airProductChannelOnlineSelfPlatform : airProductChannelOnlineSelfPlatforms) {
                    AirProductOnlineSelfPlatformData airProductOnlineSelfPlatformData = new AirProductOnlineSelfPlatformData();
                    AirProductSaleStrategyDataInfoData airProductSaleStrategyDataInfoData = EntityUtil.copy(airProductChannelOnlineSelfPlatform,
                            AirProductSaleStrategyDataInfoData.class);
                    airProductOnlineSelfPlatformData.setAirProductSaleStrategyDataInfoData(airProductSaleStrategyDataInfoData);
                    airProductOnlineSelfPlatformData.setChannelId(airProductChannelOnlineSelfPlatform.getChannelId());
                    airProductOnlineSelfPlatformData.setChannelName(airProductChannelOnlineSelfPlatform.getChannelName());
                    airProductOnlineSelfPlatformDataList.add(airProductOnlineSelfPlatformData);
                }
            }

            /**祖装线上第三方平台数据*/
            List<AirProductOnlineThirdPlatformData> airProductOnlineThirdPlatformDataList = Lists.newArrayList();
            List<AirProductChannelOnlineThirdPlatform> airProductChannelOnlineThirdPlatforms = thirdPlatformMap.get(airProductSaleStrategy.getId());
            if (CollectionUtil.isNotEmpty(airProductChannelOnlineThirdPlatforms)) {
                for (AirProductChannelOnlineThirdPlatform airProductChannelOnlineThirdPlatform : airProductChannelOnlineThirdPlatforms) {
                    AirProductOnlineThirdPlatformData airProductOnlineThirdPlatformData = new AirProductOnlineThirdPlatformData();
                    AirProductSaleStrategyDataInfoData airProductSaleStrategyDataInfoData = EntityUtil.copy(airProductChannelOnlineThirdPlatform,
                            AirProductSaleStrategyDataInfoData.class);
                    airProductOnlineThirdPlatformData.setAirProductSaleStrategyDataInfoData(airProductSaleStrategyDataInfoData);
                    airProductOnlineThirdPlatformData.setPlatformId(airProductChannelOnlineThirdPlatform.getPlatformId());
                    airProductOnlineThirdPlatformData.setPlatformName(airProductChannelOnlineThirdPlatform.getPlatformName());
                    airProductOnlineThirdPlatformDataList.add(airProductOnlineThirdPlatformData);
                }
            }
            airProductSaleStrategyData.setAirProductChannelofflineSelfData(airProductChannelofflineSelfData);
            airProductSaleStrategyData.setAirProductChannelOfflineAgentData(airProductChannelOfflineAgentData);
            airProductSaleStrategyData.setAirProductOnlineSelfPlatformDataList(airProductOnlineSelfPlatformDataList);
            airProductSaleStrategyData.setAirProductOnlineThirdPlatformDataList(airProductOnlineThirdPlatformDataList);
            airProductSaleStrategyDataList.add(airProductSaleStrategyData);
        }
        airProductSaleStrategyDto.setAirProductSaleStrategyReqList(airProductSaleStrategyDataList);
        return Result.success(airProductSaleStrategyDto);
    }


    @Override
    public Result<PageResponse<AirRecommendListDTO>> recommendList(AirProductRecommendListReq req, TokenUser tokenUser) {
        Page<AirRecommendListDTO> page = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p.sell_status", 1);
        queryWrapper.eq("p.recommend_status", 1);
        queryWrapper.eq("p.is_deleted", IsDeletedCode.NO.getCode());
        Page<AirRecommendListDTO> iPage = airProductMapper.queryRecommend(page, queryWrapper);
        List<AirRecommendListDTO> airRecommendListDTOList = iPage.getRecords();
        if (CollectionUtil.isEmpty(airRecommendListDTOList)) {
            return Result.success(new PageResponse<AirRecommendListDTO>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                    iPage.getTotal(), iPage.getCurrent(), iPage.getSize()));
        }
        /**查詢機票最低價*/
        Set<Long> productIds = Sets.newHashSet();
        for (AirRecommendListDTO airRecommendListDTO : airRecommendListDTOList) {
            productIds.add(airRecommendListDTO.getId());
        }
        AirProductCostQueryReq airProductCostQueryReq = new AirProductCostQueryReq();
        airProductCostQueryReq.setEndDate(LocalDate.now());
        airProductCostQueryReq.setStarDate(LocalDate.now());
        airProductCostQueryReq.setChannelType(req.getChannelType().getType());
        airProductCostQueryReq.setIsMark(true);
        airProductCostQueryReq.setRelationId(tokenUser != null ? tokenUser.getId() : null);
        airProductCostQueryReq.setProductIds(Arrays.asList(productIds.toArray(new Long[productIds.size()])));
        List<AirProductPriceDTO> airProductPriceDTOList = iAirProductCostService.queryProductCost(airProductCostQueryReq);
        Map<Long, AirProductPriceDTO> airProductPriceDTOMap = Maps.newHashMap();
        for (AirProductPriceDTO airProductPriceDTO : airProductPriceDTOList) {
            airProductPriceDTOMap.put(airProductPriceDTO.getProductId(), airProductPriceDTO);
        }
        List<AirRecommendListDTO> resultList = Lists.newArrayList();
        for (AirRecommendListDTO airRecommendListDTO : airRecommendListDTOList) {
            AirProductPriceDTO airProductPriceDTO = airProductPriceDTOMap.get(airRecommendListDTO.getId());

            if (null != airProductPriceDTO) {
                if (ObjectUtils.isNotEmpty(airProductPriceDTO.getForbidTheSale()) && airProductPriceDTO.getForbidTheSale()) {
                    continue;
                }

                List<AirProductPriceTouristDTO> airProductPriceTouristDTOList = airProductPriceDTO.getAirProductPriceTouristDTOList();
                BigDecimal lowPrice = null;
                for (AirProductPriceTouristDTO airProductPriceTouristDTO : airProductPriceTouristDTOList) {
                    List<AirProductPriceDateDTO> airProductPriceDateDTOList = airProductPriceTouristDTO.getAirProductPriceDateDTOList();
                    for (AirProductPriceDateDTO airProductPriceDateDTO : airProductPriceDateDTOList) {
                        if (null == lowPrice) {
                            lowPrice = airProductPriceDateDTO.getPrice();
                        } else {
                            if (lowPrice.compareTo(airProductPriceDateDTO.getPrice()) > 0) {
                                lowPrice = airProductPriceDateDTO.getPrice();
                            }
                        }
                    }
                }
                airRecommendListDTO.setLowPrice(lowPrice);
                resultList.add(airRecommendListDTO);
            }
        }
        if (CollectionUtil.isEmpty(resultList)) {
            return Result.success(new PageResponse<AirRecommendListDTO>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                    iPage.getTotal(), iPage.getCurrent(), iPage.getSize()));
        }
        return Result.success(new PageResponse<AirRecommendListDTO>(airRecommendListDTOList, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                iPage.getTotal(), iPage.getCurrent(), iPage.getSize()));
    }


    @Override
    public Result<List<AirBookingListDTO>> queryBookingList(AirBookingListReq req, TokenUser tokenUser) {
        List<AirBookingListDTO> airBookingListDTOList = Lists.newArrayList();
        //暂时不支持往返查询
        if (req.getTripType().intValue() == AirOrderTripType.RETURN.getCode().intValue()) {
            return Result.failed(SystemError.SYS_400);
        }
        if (null == req.getSaleUserId() && tokenUser != null) {
            req.setSaleUserId(tokenUser.getId());
        }
        req.setPageSize(100);//默认查询一百条
        Page<AirBookingListQueryDTO> page = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<AirBookingListQueryDTO> queryWrapper = new QueryWrapper();
        queryWrapper.eq("tp.sell_status", 1);
        queryWrapper.eq("tp.is_deleted", IsDeletedCode.NO.getCode());
        queryWrapper.in(ObjectUtils.isNotEmpty(req.getCompanyIds()), "tf.company_id", req.getCompanyIds());
        queryWrapper.in(ObjectUtils.isNotEmpty(req.getCabinClass()), "tp.cabin_class", req.getCabinClass());
        queryWrapper.eq(ObjectUtils.isNotEmpty(req.getDepCityId()), "tf.dep_city_id", req.getDepCityId());
        queryWrapper.eq(ObjectUtils.isNotEmpty(req.getArrCityId()), "tf.arr_city_id", req.getArrCityId());
        queryWrapper.eq(ObjectUtils.isNotEmpty(req.getProductId()), "tp.id", req.getProductId());
        //如果要查打包产品  不允许打包的不返回  反之只不返回只允许打包的
        if (req.isPackStatus()) {
            queryWrapper.ne("tp.pack_status", 2);
        } else {
            queryWrapper.ne("tp.pack_status", 3);
        }
        List<AirBookingListDateReq> airBookingListDateReqList = req.getAirBookingListDateReqList();
        if (CollectionUtil.isNotEmpty(airBookingListDateReqList)) {
            queryWrapper.and(wrapper -> {
                wrapper.and(nameAgeQueryWrapper -> {
                    for (AirBookingListDateReq airBookingListDateReq : airBookingListDateReqList) {
                        nameAgeQueryWrapper.or(itemWrapper -> {
                            itemWrapper.ge("tf.dep_time ", airBookingListDateReq.getStartTime());
                            itemWrapper.le("tf.arr_time ", airBookingListDateReq.getEndTime());
                        });
                    }
                });
            });
        }
        Page<AirBookingListQueryDTO> airBookingListQueryDTOPage = airProductMapper.queryBooking(page, queryWrapper);
        List<AirBookingListQueryDTO> bookingListQueryDTOPageRecords = airBookingListQueryDTOPage.getRecords();
        if (CollectionUtil.isEmpty(bookingListQueryDTOPageRecords)) {
            return Result.success(Lists.newArrayList());
        }
        Set<Long> productIds = Sets.newHashSet();
        for (AirBookingListQueryDTO bookingListQueryDTOPageRecord : bookingListQueryDTOPageRecords) {
            productIds.add(bookingListQueryDTOPageRecord.getProductId());
        }
        AirProductCostQueryReq airProductCostQueryReq = new AirProductCostQueryReq();
        airProductCostQueryReq.setEndDate(req.getDepDate());
        airProductCostQueryReq.setStarDate(req.getDepDate());
        airProductCostQueryReq.setChannelType(req.getChannelType());
        airProductCostQueryReq.setIsMark(true);
        airProductCostQueryReq.setRelationId(req.getSaleUserId());
        List<AirBookingListReq.TouristTypeValue> touristTypeIds = req.getTouristTypeIds();
        List<Long> touristList = Lists.newArrayList();
        for (AirBookingListReq.TouristTypeValue touristTypeId : touristTypeIds) {
            touristList.add(touristTypeId.getTouristType());
        }
        if (req.getTicketType().intValue() == AirBookingTicketType.TICKET_COMPRE.getType().intValue()) {
            if (!touristList.contains(AirTouristType.ADULT.getType().longValue())) {
                return Result.failed(SystemError.AIR_PRODUCT_12020);
            }
        } else if (req.getTicketType().intValue() == AirBookingTicketType.SERVANT_COMPRE.getType().intValue()) {
            if (!touristList.contains(AirTouristType.SERVANT.getType().longValue())) {
                return Result.failed(SystemError.AIR_PRODUCT_12020);
            }
        } else if (req.getTicketType().intValue() == AirBookingTicketType.STUDENT.getType().intValue()) {
            if (!touristList.contains(AirTouristType.STUDENT.getType().longValue())) {
                return Result.failed(SystemError.AIR_PRODUCT_12020);
            }
        } else if (req.getTicketType().intValue() == AirBookingTicketType.BUSINESS.getType().intValue()) {
            if (!touristList.contains(AirTouristType.BUSINESS.getType().longValue())) {
                return Result.failed(SystemError.AIR_PRODUCT_12020);
            }
        } else if (req.getTicketType().intValue() == AirBookingTicketType.WORKHOLIDAY.getType().intValue()) {
            if (!touristList.contains(AirTouristType.WORKHOLIDAY.getType().longValue())) {
                return Result.failed(SystemError.AIR_PRODUCT_12020);
            }
        }
        airProductCostQueryReq.setTouristTypeIds(touristList);
        airProductCostQueryReq.setProductIds(Arrays.asList(productIds.toArray(new Long[productIds.size()])));
        List<AirProductPriceDTO> airProductPriceDTOList = iAirProductCostService.queryProductCost(airProductCostQueryReq);
        System.out.println("查询预订 价格查询返回结果--->" + JSON.toJSONString(airProductPriceDTOList));
        if (CollectionUtils.isEmpty(airProductPriceDTOList)) return Result.success(Lists.newArrayList());
        Map<Long, AirProductPriceDTO> productPriceMap = Maps.newHashMap();
        for (AirProductPriceDTO airProductPriceDTO : airProductPriceDTOList) {
            productPriceMap.put(airProductPriceDTO.getProductId(), airProductPriceDTO);
        }

        Map<Long, AirBookingListDTO> airBookingListDTOMap = Maps.newHashMap();
        //按照航班信息 聚合产品
        for (AirBookingListQueryDTO bookingListQueryDTOPageRecord : bookingListQueryDTOPageRecords) {
            AirBookingListDTO airBookingListDTO = airBookingListDTOMap.get(bookingListQueryDTOPageRecord.getFlightId());
            BigDecimal lowPrice = null;
            if (null == airBookingListDTO) {
                airBookingListDTO = EntityUtil.copy(bookingListQueryDTOPageRecord, AirBookingListDTO.class);
                AirBookingListProductDTO airBookingListProductDTO = EntityUtil.copy(bookingListQueryDTOPageRecord, AirBookingListProductDTO.class);
                //组装价格
                AirProductPriceDTO airProductPriceDTO = productPriceMap.get(airBookingListProductDTO.getProductId());
                List<AirProductPriceTouristDTO> airProductPriceTouristDTOList = airProductPriceDTO.getAirProductPriceTouristDTOList();
                if (CollectionUtil.isEmpty(airProductPriceTouristDTOList)) {//没有价格的产品不添加
                    continue;
                }
                List<AirBookingListTouristDTO> airBookingListTouristDTOList = Lists.newArrayList();
                for (AirProductPriceTouristDTO airProductPriceTouristDTO : airProductPriceTouristDTOList) {
                    if (CollectionUtil.isNotEmpty(airProductPriceTouristDTO.getAirProductPriceDateDTOList())) {
                        BigDecimal price = airProductPriceTouristDTO.getAirProductPriceDateDTOList().get(0).getPrice();
                        if (null == lowPrice) {
                            lowPrice = price;
                        } else if (lowPrice.compareTo(price) > 0) {
                            lowPrice = price;
                        }
                        AirProductPriceDateDTO airProductPriceDateDTO = airProductPriceTouristDTO.getAirProductPriceDateDTOList().get(0);
                        airBookingListProductDTO.setStock(airProductPriceDateDTO.getDailyStock());
                        AirBookingListTouristDTO airBookingListTouristDTO = new AirBookingListTouristDTO();
                        airBookingListTouristDTO.setCostPrice(price);
                        airBookingListTouristDTO.setTouristTypeId(airProductPriceTouristDTO.getAirTouristTypeId());
                        airBookingListTouristDTO.setCurrencyId(airProductPriceDateDTO.getCurrencyId());
                        airBookingListTouristDTO.setCurrencyName(airProductPriceDateDTO.getCurrencyName());
                        airBookingListTouristDTO.setDate(airProductPriceDateDTO.getDate());
                        airBookingListTouristDTO.setTouristTypeName(airProductPriceTouristDTO.getAirTouristTypeName());
                        airBookingListTouristDTO.setAirProductCostTaxationDTOList(airProductPriceDateDTO.getAirProductCostTaxationDTOList());
                        airBookingListTouristDTOList.add(airBookingListTouristDTO);
                    }
                }
                airBookingListProductDTO.setAirBookingListTouristDTOList(airBookingListTouristDTOList);
                airBookingListProductDTO.setAirProductPriceSettingsDTO(EntityUtil.copy(airProductPriceDTO.getAirProductPriceSettingsDTO(), AirProductPriceSettingsDTO.class));
                List<AirBookingListProductDTO> airBookingListProductDTOList = Lists.newArrayList();
                airBookingListProductDTOList.add(airBookingListProductDTO);
                airBookingListDTO.setAirBookingListProductDTOList(airBookingListProductDTOList);
            } else {
                lowPrice = airBookingListDTO.getLowPrice();
                AirBookingListProductDTO airBookingListProductDTO = EntityUtil.copy(bookingListQueryDTOPageRecord, AirBookingListProductDTO.class);
                //组装价格
                AirProductPriceDTO airProductPriceDTO = productPriceMap.get(airBookingListProductDTO.getProductId());
                List<AirProductPriceTouristDTO> airProductPriceTouristDTOList = airProductPriceDTO.getAirProductPriceTouristDTOList();
                if (CollectionUtil.isEmpty(airProductPriceTouristDTOList)) {//没有价格的产品不添加
                    continue;
                }
                List<AirBookingListTouristDTO> airBookingListTouristDTOList = Lists.newArrayList();
                for (AirProductPriceTouristDTO airProductPriceTouristDTO : airProductPriceTouristDTOList) {
                    if (CollectionUtil.isNotEmpty(airProductPriceTouristDTO.getAirProductPriceDateDTOList())) {
                        AirBookingListTouristDTO airBookingListTouristDTO = new AirBookingListTouristDTO();
                        BigDecimal price = airProductPriceTouristDTO.getAirProductPriceDateDTOList().get(0).getPrice();
                        if (null == lowPrice) {
                            lowPrice = price;
                        } else if (lowPrice.compareTo(price) > 0) {
                            lowPrice = price;
                        }
                        AirProductPriceDateDTO airProductPriceDateDTO = airProductPriceTouristDTO.getAirProductPriceDateDTOList().get(0);
                        airBookingListProductDTO.setStock(airProductPriceDateDTO.getDailyStock());
                        airBookingListTouristDTO.setCostPrice(price);
                        airBookingListTouristDTO.setTouristTypeId(airProductPriceTouristDTO.getAirTouristTypeId());
                        airBookingListTouristDTO.setTouristTypeName(airProductPriceTouristDTO.getAirTouristTypeName());
                        airBookingListTouristDTO.setCurrencyId(airProductPriceDateDTO.getCurrencyId());
                        airBookingListTouristDTO.setCurrencyName(airProductPriceDateDTO.getCurrencyName());
                        airBookingListTouristDTO.setDate(airProductPriceDateDTO.getDate());
                        airBookingListTouristDTO.setAirProductCostTaxationDTOList(airProductPriceDateDTO.getAirProductCostTaxationDTOList());
                        airBookingListTouristDTOList.add(airBookingListTouristDTO);
                    }
                }
                airBookingListProductDTO.setAirBookingListTouristDTOList(airBookingListTouristDTOList);
                airBookingListProductDTO.setAirProductPriceSettingsDTO(EntityUtil.copy(airProductPriceDTO.getAirProductPriceSettingsDTO(), AirProductPriceSettingsDTO.class));
                List<AirBookingListProductDTO> airBookingListProductDTOList = airBookingListDTO.getAirBookingListProductDTOList();
                airBookingListProductDTOList.add(airBookingListProductDTO);
                airBookingListDTO.setAirBookingListProductDTOList(airBookingListProductDTOList);
            }
            airBookingListDTO.setLowPrice(lowPrice);
            airBookingListDTOMap.put(bookingListQueryDTOPageRecord.getFlightId(), airBookingListDTO);
        }
        for (AirBookingListDTO value : airBookingListDTOMap.values()) {
            airBookingListDTOList.add(value);
        }
        return Result.success(airBookingListDTOList);
    }

    @Override
    public Result<List<AirBookingTicketTypeOpDTO>> queryTicketOp() {
        List<AirBookingTicketTypeOpDTO> airBookingTicketTypeDTOList = Lists.newArrayList();
        /**雇佣机票*/
        AirBookingTicketTypeOpDTO airBookingTicketTypeOpDTO = new AirBookingTicketTypeOpDTO();
        airBookingTicketTypeOpDTO.setBookingTicketType(AirBookingTicketType.TICKET_COMPRE.getType());
        airBookingTicketTypeOpDTO.setBookingTicketTypeName(AirBookingTicketType.TICKET_COMPRE.getDesc());
        List<AirBookingTicketTypeToursDTO> airBookingTicketTypeToursDTOList = Lists.newArrayList();
        //婴儿
        AirBookingTicketTypeToursDTO airBookingTicketTypeToursDTO = new AirBookingTicketTypeToursDTO();
        airBookingTicketTypeToursDTO.setIsBaby(1);
        airBookingTicketTypeToursDTO.setTouristType(AirTouristType.BABY.getType());
        airBookingTicketTypeToursDTO.setTouristTypeName(AirTouristType.BABY.getName());
        airBookingTicketTypeToursDTO.setTouristTypePageName("帶嬰兒（14天-2歲）嬰兒票需待人工出票");
        airBookingTicketTypeToursDTO.setNeedCertificates(true);
        airBookingTicketTypeToursDTOList.add(airBookingTicketTypeToursDTO);
        //儿童
        AirBookingTicketTypeToursDTO airBookingTicketTypeToursDTO1 = new AirBookingTicketTypeToursDTO();
        airBookingTicketTypeToursDTO1.setTouristType(AirTouristType.CHILD.getType());
        airBookingTicketTypeToursDTO1.setTouristTypeName(AirTouristType.CHILD.getName());
        airBookingTicketTypeToursDTO1.setTouristTypePageName("小童(2-12岁)");
        airBookingTicketTypeToursDTO1.setNeedCertificates(true);
        airBookingTicketTypeToursDTOList.add(airBookingTicketTypeToursDTO1);
        //成人
        AirBookingTicketTypeToursDTO airBookingTicketTypeToursDTO2 = new AirBookingTicketTypeToursDTO();
        airBookingTicketTypeToursDTO2.setTouristType(AirTouristType.ADULT.getType());
        airBookingTicketTypeToursDTO2.setTouristTypeName(AirTouristType.ADULT.getName());
        airBookingTicketTypeToursDTO2.setTouristTypePageName(AirTouristType.ADULT.getName());
        airBookingTicketTypeToursDTOList.add(airBookingTicketTypeToursDTO2);

        airBookingTicketTypeOpDTO.setAirBookingTicketTypeToursDTOList(airBookingTicketTypeToursDTOList);
        airBookingTicketTypeDTOList.add(airBookingTicketTypeOpDTO);

        /**雇佣机票*/
        AirBookingTicketTypeOpDTO airBookingTicketTypeOpDTO1 = new AirBookingTicketTypeOpDTO();
        airBookingTicketTypeOpDTO1.setBookingTicketType(AirBookingTicketType.SERVANT_COMPRE.getType());
        airBookingTicketTypeOpDTO1.setBookingTicketTypeName(AirBookingTicketType.SERVANT_COMPRE.getDesc());
        List<AirBookingTicketTypeToursDTO> airBookingTicketTypeToursDTOList1 = Lists.newArrayList();
        AirBookingTicketTypeToursDTO airBookingTicketTypeToursDTO3 = new AirBookingTicketTypeToursDTO();
        airBookingTicketTypeToursDTO3.setTouristType(AirTouristType.SERVANT.getType());
        airBookingTicketTypeToursDTO3.setTouristTypeName(AirTouristType.SERVANT.getName());
        airBookingTicketTypeToursDTO3.setTouristTypePageName("成人");
        airBookingTicketTypeToursDTO3.setNeedCertificates(true);
        airBookingTicketTypeToursDTOList1.add(airBookingTicketTypeToursDTO3);
        airBookingTicketTypeOpDTO1.setAirBookingTicketTypeToursDTOList(airBookingTicketTypeToursDTOList1);
        airBookingTicketTypeDTOList.add(airBookingTicketTypeOpDTO1);

        /**学生机票*/
        AirBookingTicketTypeOpDTO airBookingTicketTypeOpDTO2 = new AirBookingTicketTypeOpDTO();
        airBookingTicketTypeOpDTO2.setBookingTicketType(AirBookingTicketType.STUDENT.getType());
        airBookingTicketTypeOpDTO2.setBookingTicketTypeName(AirBookingTicketType.STUDENT.getDesc());
        List<AirBookingTicketTypeToursDTO> airBookingTicketTypeToursDTOList2 = Lists.newArrayList();
        AirBookingTicketTypeToursDTO airBookingTicketTypeToursDTO4 = new AirBookingTicketTypeToursDTO();
        airBookingTicketTypeToursDTO4.setTouristType(AirTouristType.STUDENT.getType());
        airBookingTicketTypeToursDTO4.setTouristTypeName(AirTouristType.STUDENT.getName());
        airBookingTicketTypeToursDTO4.setTouristTypePageName("成人");
        airBookingTicketTypeToursDTO4.setNeedCertificates(true);
        airBookingTicketTypeToursDTOList2.add(airBookingTicketTypeToursDTO3);
        airBookingTicketTypeOpDTO2.setAirBookingTicketTypeToursDTOList(airBookingTicketTypeToursDTOList2);
        airBookingTicketTypeDTOList.add(airBookingTicketTypeOpDTO2);

        /**差旅机票*/
        AirBookingTicketTypeOpDTO airBookingTicketTypeOpDTO3 = new AirBookingTicketTypeOpDTO();
        airBookingTicketTypeOpDTO3.setBookingTicketType(AirBookingTicketType.BUSINESS.getType());
        airBookingTicketTypeOpDTO3.setBookingTicketTypeName(AirBookingTicketType.BUSINESS.getDesc());
        List<AirBookingTicketTypeToursDTO> airBookingTicketTypeToursDTOList3 = Lists.newArrayList();
        AirBookingTicketTypeToursDTO airBookingTicketTypeToursDTO5 = new AirBookingTicketTypeToursDTO();
        airBookingTicketTypeToursDTO5.setTouristType(AirTouristType.BUSINESS.getType());
        airBookingTicketTypeToursDTO5.setTouristTypeName(AirTouristType.BUSINESS.getName());
        airBookingTicketTypeToursDTO5.setTouristTypePageName("成人");
        airBookingTicketTypeToursDTO5.setNeedCertificates(true);
        airBookingTicketTypeToursDTOList3.add(airBookingTicketTypeToursDTO5);
        airBookingTicketTypeOpDTO3.setAirBookingTicketTypeToursDTOList(airBookingTicketTypeToursDTOList3);
        airBookingTicketTypeDTOList.add(airBookingTicketTypeOpDTO3);

        /**假期机票*/
        AirBookingTicketTypeOpDTO airBookingTicketTypeOpDTO4 = new AirBookingTicketTypeOpDTO();
        airBookingTicketTypeOpDTO4.setBookingTicketType(AirBookingTicketType.WORKHOLIDAY.getType());
        airBookingTicketTypeOpDTO4.setBookingTicketTypeName(AirBookingTicketType.WORKHOLIDAY.getDesc());
        List<AirBookingTicketTypeToursDTO> airBookingTicketTypeToursDTOList4 = Lists.newArrayList();
        AirBookingTicketTypeToursDTO airBookingTicketTypeToursDTO6 = new AirBookingTicketTypeToursDTO();
        airBookingTicketTypeToursDTO6.setTouristType(AirTouristType.WORKHOLIDAY.getType());
        airBookingTicketTypeToursDTO6.setTouristTypeName(AirTouristType.WORKHOLIDAY.getName());
        airBookingTicketTypeToursDTO6.setTouristTypePageName("成人");
        airBookingTicketTypeToursDTO6.setNeedCertificates(true);
        airBookingTicketTypeToursDTOList4.add(airBookingTicketTypeToursDTO6);
        airBookingTicketTypeOpDTO4.setAirBookingTicketTypeToursDTOList(airBookingTicketTypeToursDTOList4);
        airBookingTicketTypeDTOList.add(airBookingTicketTypeOpDTO4);
        return Result.success(airBookingTicketTypeDTOList);
    }


    /**
     * 删除已经存在的策略 用于新增修改前进行删除 避免重复
     *
     * @param airProductIds 机票手动产品id集合
     * @return
     */
    private Result deleteAirProductStrate(List<Long> airProductIds) {
        /**删除上架策略主表存在的数据*/
        QueryWrapper<AirProductSaleStrategy> saleStrategyQueryWrapper = new QueryWrapper<>();
        saleStrategyQueryWrapper.lambda().in(AirProductSaleStrategy::getProductId, airProductIds);
        airProductSaleStrategyMapper.delete(saleStrategyQueryWrapper);
        /**删除上架策略时间存在的数据*/
        QueryWrapper<AirProductSaleStrategyVaildDate> saleStrategyVaildDateQueryWrapper = new QueryWrapper<>();
        saleStrategyVaildDateQueryWrapper.lambda().in(AirProductSaleStrategyVaildDate::getProductId, airProductIds);
        airProductSaleStrategyVaildDateMapper.delete(saleStrategyVaildDateQueryWrapper);
        /**删除上架策略机票线下渠道类型存在的数据*/
        QueryWrapper<AirProductChannelOffline> channelOfflineQueryWrapper = new QueryWrapper<>();
        channelOfflineQueryWrapper.lambda().in(AirProductChannelOffline::getProductId, airProductIds);
        airProductChannelOfflineMapper.delete(channelOfflineQueryWrapper);
        /**删除上架策略线下代理商数据*/
        QueryWrapper<AirProductChannelOfflineAgentCustom> channelOfflineAgentCustomQueryWrapper = new QueryWrapper<>();
        channelOfflineAgentCustomQueryWrapper.lambda().in(AirProductChannelOfflineAgentCustom::getProductId, airProductIds);
        airProductChannelOfflineAgentCustomMapper.delete(channelOfflineAgentCustomQueryWrapper);
        /**删除上架策略线下自营数据*/
        QueryWrapper<AirProductChannelOfflineSelfCustom> channelOfflineSelfCustomQueryWrapper = new QueryWrapper<>();
        channelOfflineSelfCustomQueryWrapper.lambda().in(AirProductChannelOfflineSelfCustom::getProductId, airProductIds);
        airProductChannelOfflineSelfCustomMapper.delete(channelOfflineSelfCustomQueryWrapper);
        /**删除上架策略线上官方平台数据*/
        QueryWrapper<AirProductChannelOnlineSelfPlatform> channelOnlineSelfPlatformQueryWrapper = new QueryWrapper<>();
        channelOnlineSelfPlatformQueryWrapper.lambda().in(AirProductChannelOnlineSelfPlatform::getProductId, airProductIds);
        airProductChannelOnlineSelfPlatformMapper.delete(channelOnlineSelfPlatformQueryWrapper);
        /**删除上架策略线上第三方平台数据*/
        QueryWrapper<AirProductChannelOnlineThirdPlatform> channelOnlineThirdPlatformQueryWrapper = new QueryWrapper<>();
        channelOnlineThirdPlatformQueryWrapper.lambda().in(AirProductChannelOnlineThirdPlatform::getProductId, airProductIds);
        airProductChannelOnlineThirdPlatformMapper.delete(channelOnlineThirdPlatformQueryWrapper);
        return Result.success();
    }

    @Override
    public List<AirProductDTO> queryProductList(List<Long> productIds) {
        QueryWrapper<AirProduct> airProductQueryWrapper = new QueryWrapper<>();
        airProductQueryWrapper.lambda().in(AirProduct::getId, productIds);
        airProductQueryWrapper.lambda().eq(AirProduct::getSellStatus, 1);
        airProductQueryWrapper.lambda().eq(AirProduct::getApprovalStatus, 5);
        List<AirProduct> airProductList = airProductMapper.selectList(airProductQueryWrapper);
        List<AirProductDTO> airProductDTOList = EntityUtil.copyList(airProductList, AirProductDTO.class);
        return airProductDTOList;
    }

    @Override
    public Result<PageResponse<OperationsCenterGetProductListDTO>> operationsCenterGetProductList(AirProductOperationsCenterListReq req) {
        Page<AirProductListDTO> iPage = airProductMapper.queryProcutList(
                new Page<AirProductListDTO>(req.getPageNo(), req.getPageSize()),
                Wrappers.<AirProductListDTO>query()
                        .eq(StringUtils.isNotBlank(req.getProductNumber()), "tp.code", req.getProductNumber())
                        .eq(Objects.nonNull(req.getDepCityId()), "tf.dep_city_id", req.getDepCityId())
                        .eq(Objects.nonNull(req.getArrCityId()), "tf.arr_city_id", req.getArrCityId())
                        .eq(Objects.nonNull(req.getCabinClass()), "tp.cabin_class", req.getCabinClass())
                        .eq(Objects.nonNull(req.getSupplierId()), "tp.supplier_id", req.getSupplierId())
                        .eq(Objects.nonNull(req.getCompanyId()), "tf.company_id", req.getCompanyId())
                        .eq(StringUtils.isNotBlank(req.getFlightNumber()), "tf.flight_number", req.getFlightNumber())
        );
        List<OperationsCenterGetProductListDTO> list =
                EntityUtil.copyList(iPage.getRecords(), OperationsCenterGetProductListDTO.class);
        return Result.success(new PageResponse<OperationsCenterGetProductListDTO>(list,
                iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                iPage.getTotal(), iPage.getCurrent(), iPage.getSize()));
    }

    @Override
    public Result<List<OperationsCenterGetProductListDTO>> operationsCenterGetProductByIds(List<Long> productIds) {
        if (CollectionUtils.isEmpty(productIds)) return Result.success(Lists.newArrayList());
        Page<AirProductListDTO> iPage =
                airProductMapper.queryProcutList(new Page<>(1, productIds.size()), Wrappers.query().in("tp.id", productIds));
        return Result.success(EntityUtil.copyList(iPage.getRecords(), OperationsCenterGetProductListDTO.class));
    }


    @Override
    public Result productExamine(AirProductExamineReq req, TokenUser currentUser) {
        ApprovalStatus status = ApprovalStatus.getDefined(req.getStatus());
        Assert.nonNull(status, SystemError.WORK_FLOW_4002);
        //调用审批系统
        Result<ApprovalCheckDTO> result = iSysApprovalService.check(req.getApprovalId(), currentUser.getId(), status.getCode(), req.getReason());
        Assert.isTrue(result.isSuccess(), SystemError.getDefined(result.getCode()));
        //如果不是最后一步 直接返回成功
        if (!result.getData().getIsFinish()) return Result.success();
        //是最后一步已完成 修改产品状态
        AirProduct airProduct = baseMapper.selectById(req.getProductId());
        Assert.nonNull(airProduct, SystemError.AIR_PRODUCT_12004);
        //校验产品状态 --只有审批中的可以修改审批状态
        Assert.isTrue(
                ApprovalStatus.REVIEWING.getCode().equals(airProduct.getApprovalStatus()),
                SystemError.WORK_FLOW_4001);
        AirProduct update = new AirProduct();
        update.setId(airProduct.getId());
        //...机票这边定义的审批状态跟审批系统的不一致 需要转换一下...
        Integer approvalStatus = null;
        switch (status) {
            case REVIEW_YES:
                approvalStatus = 5;
                break;
            case REVIEW_NO:
                approvalStatus = 4;
                break;
            default:
                approvalStatus = 1;
                break;
        }
        update.setApprovalStatus(approvalStatus);
        update.setSellStatus(1);
        int i = baseMapper.updateById(update);
        Assert.isTrue(i > 0, SystemError.SYS_437);
        return Result.success();
    }

    @Override
    public AirProductInfoDTO getById(Long productId) {
        AirProduct airProduct = baseMapper.selectById(productId);
        return EntityUtil.copy(airProduct,AirProductInfoDTO.class);
    }


}
